C++几种计时器
1.使用clock()
#include <Windows.h>//包含sleep()
#include <time.h>//包含clock()
#include <iostream>
//函数原型clock_t clock(void)
int main()
{
clock_t start,end;
start = clock();
Sleep(1000);
end = clock();
double last = double(end-start);
std::cout << "程序耗时:"<< last << "ms" << endl;
}
2.使用GetTickCount()
#include <Windows.h>//包含sleep(),GetTickCount()
#include <iostream>
//函数原型DWORD GetTickCount(void)
int main()
{
DWORD start,stop;
double start = GetTickCount();
Sleep(2000);
double end = GetTickCount();
double last = douuble(end-start);
std::cout<< "程序耗时:" << last << "ms" << endl;
}
3.使用time()
#include <Windows.h>//包含sleep()
#include <time.h>//包含time()
#include <iostream>
//函数原型time_t time(time_t *arg);
int main()
{
time_t start, stop;
double durationTime;
start = time(NULL);
Sleep(2000);
end = time(NULL);
durationTime = (double)(end- start);
std::cout << "程序耗时:" << durationTime << " s" << endl;
}
4.使用steady_clock::now()
#include <chrono>//包含steady_clock::now()
#include <iostream>
int main()
{
using namespace std::chrono;
steady_clock::time_point start = steady_clock::now();
Sleep(1000);
steady_clock::time_point end = steady_clock::now();
duration<double> time_span = duration_cast<duration<double>>(end-start);
std::cout<< "程序耗时:" << time_span.count() << "s";
}
5.使用QueryPerformance
#include <Windows.h>//包含sleep(),QueryPerformance
#include <iostream>
int main()
{
LARGE_INTEGER cpuFreq;
LARGE_INTEGER startTime;
LARGE_INTEGER endTime;
QueryPerformanceFrequency(&cpuFreq);
QueryPerformanceCounter(&startTime);
Sleep(1000);
QueryPerformanceCounter(&endTime);
double last = (((endTime.QuadPart - startTime.QuadPart) * 1000000) / cpuFreq.QuadPart);
std::cout << "程序耗时:"<< last << " us" << endl;
}