1、毫秒級
- 使用GetTickCount()獲取系統啟動所經過的毫秒數
#include<iostream> using namespace std; int main(){ DWORD start= ::GetTickCount(); //獲取毫秒級數目 Sleep(1000); cout << ::GetTickCount() - start<< endl; system("pause"); }
2. 使用clock()
#include <iostream> #include <time.h> #include <Windows.h> using namespace std; int main(){ clock_t start; start = clock(); Sleep(1000); cout<<clock()-start<<" ms"<<endl; system("pause"); }
2、微秒級
- 先用QueryPerformanceFrequency()獲取時鍾周期再調用QueryPerformanceCounter()獲取CPU從開機以來執行的時鍾周期數
#include <stdio.h> #include <math.h> #include <windows.h> using namespace std; void main() { LARGE_INTEGER cpuFreq; LARGE_INTEGER startTime; LARGE_INTEGER endTime; double rumTime=0.0; QueryPerformanceFrequency(&cpuFreq); QueryPerformanceCounter(&startTime); Sleep(1000); QueryPerformanceCounter(&endTime); rumTime = (((endTime.QuadPart - startTime.QuadPart) * 1000.0f) / cpuFreq.QuadPart); cout << rumtTime << " ms" << endl; }
