C++ 入門指南 4.01

練習 18.10 參考程式 - 練習標準程式庫的時間相關程式

// 引入標準程式庫中相關的輸入、輸出程式
#include <iostream>
// 引入標準程式庫中相關的時間處理程式
#include <chrono>
// 引入標準程式庫中相關的並行計算程式
#include <thread>

// cout 為 std 中的輸出物件
using std::cout;
// endl 為 std 中的斷行符號
using std::endl;
// sleep_until 為 std 中的暫停函數
using std::this_thread::sleep_until;
// system_clock 為 std 中的時間處理型態
using std::chrono::system_clock;
// high_resolution_clock 為 std 中的時間處理型態
using std::chrono::high_resolution_clock;
// duration_cast 為 std 中的時間處理型態
using std::chrono::duration_cast;
// milliseconds 為 std 中的時間處理型態
using std::chrono::milliseconds;
// seconds 為 std 中的計時函數
using std::chrono::seconds;

int main(void) {
    // 取得以下程式開始執行時間
    auto t1 = high_resolution_clock::now();

    // 顯示計時起始訊息
    cout << "開始計時5秒...." << endl;
    // 計時五秒
    for (int i = 5; i >= 1; i--) {
        cout << i << endl;
        sleep_until(system_clock::now() + seconds(1));
    }
    // 顯示計時結束訊息
    cout << "計時結束" << endl;

    // 取得以上程式結束時間
    auto t2 = high_resolution_clock::now();
    // 計算時間差
    auto int_ms = duration_cast<milliseconds>(t2 - t1);
    // 顯示時間差
    cout << endl;
    cout << "程式總共費時";
    cout << (double) int_ms.count() / 1000;
    cout << "秒" << endl;

    // 最後回傳 0 給作業系統
    return 0;
}

/* 《程式語言教學誌》的範例程式
   http://kaiching.org/
   檔名:exercise1810.cxx
   編譯:g++ exercise1810.cxx -std=c++11
   執行:./a.out
   功能:C++入門指南單元十八的練習
   作者:張凱慶 */
回到練習題目

上一頁 練習 18.9 參考程式 - 練習標準程式庫的時間相關程式
回 C++ 入門指南 4.01 目錄
下一頁 練習 19.1 參考程式 - 練習標準程式庫的 map
回 C++ 教材
回程式語言教材首頁