C++计时器:毫秒级和微秒级

时间:2022-10-19 08:54:28

1、毫秒级

  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、微秒级

  1. 先用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;
}