一個簡單定時器的實現(C++)
阿新 • • 發佈:2018-12-31
該定時器類繼承一個Thread類(自定義),線上程函式裡,每隔一定的時間,執行一次TimerHandler.
1 setInterval 的時間間隔不能等於定時器要定時的總時間
2 Handle thread=::CreateThread(NULL,0,ThreadProc,this,0,p);
執行緒建立使用的是Win32的API,因為執行緒也只是建立一次,屬於極少建立執行緒的Case,所以可以使用。
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <iostream> #include <time.h> usingnamespace std; int main() { clock_t start = clock(); // Place your codes here... // 指定執行次數 clock_t ends = clock(); cout <<"Running Time : "<<(double)(ends - start)/ CLOCKS_PER_SEC << endl; // 每秒時鐘的跳數 cout <<"Running Time : "<<ends - start <<" ms"<<endl; // 毫秒 ms return0; }
程式很簡單,輸出的結果秒數,如果將結果乘以1000則輸出的為毫秒數.
常量CLOCKS_PER_SEC,它用來表示一秒鐘會有多少個時鐘計時單元
//而非(double)((finish
- start) / CLOCKS_PER_SEC)
先會將finish - start轉換成double型資料,然後執行"/"操作,則編譯器自動將CLOCKS_PER_SEC提升為double型,故而是兩個double資料相除
能得到正確結果。
你也可以用clock函式來計算你的機器執行一個迴圈或者處理其它事件到底花了多少時間。
在標準C/C++中,最小的計時單位是1毫秒。