C语言计时功能:六种c++计时器函数
以下所有代码都有使用Sleep()延时函数,需 #include <Windows.h>
1.使用clock(),ms级别计时器 :
double start = clock();Sleep(1000);double end = clock();double last = start - end;cout << last << "ms" << endl;
使用时需要包含头文件<ctime>
2. 使用GetTickCount(),ms级别计时器 :
double start = GetTickCount(); //计时器Sleep(2000);double end = GetTickCount();double last = start - end;cout << last << "ms" << endl;
使用时需包含<Window.h>
3.使用getTickCount(),ms级别计时器:
double start = getTickCount();//开始时间Sleep(2000);double end = getTickCount();double last = (end - start) * 1000 / getTickFrequency();cout << last << "ms" << endl;
这是opencv 所带计时器,使用时需#include <opencv2/opencv.hpp>,前面那个GetTickCount()是win的API。
4.使用time(NULL),s级别计时器:
double start, stop, durationTime;start = time(NULL);Sleep(2000);stop = time(NULL);durationTime = (double)difftime(stop, start);cout << "程序耗时:" << durationTime << " s" << endl;
需要包含<ctime>
5.微秒级计时器QueryPerformance:
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);cout << last << " us" << endl;
需要包含<Windows.h>
还可以将其封装为一个类:
class stop_watch
{
public:stop_watch(): elapsed_(0){QueryPerformanceFrequency(&freq_);}~stop_watch() {}
public:void start(){QueryPerformanceCounter(&begin_time_);}void stop(){LARGE_INTEGER end_time;QueryPerformanceCounter(&end_time);elapsed_ += (end_time.QuadPart - begin_time_.QuadPart) * 1000000 / freq_.QuadPart;}void restart(){elapsed_ = 0;start();}//微秒double elapsed(){return static_cast<double>(elapsed_);}//毫秒double elapsed_ms(){return elapsed_ / 1000.0;}//秒double elapsed_second(){return elapsed_ / 1000000.0;}private:LARGE_INTEGER freq_;LARGE_INTEGER begin_time_;long long elapsed_;
};int main()
{stop_watch watch;watch.start();Sleep(2000);watch.stop();cout << watch.elapsed() << endl;
}
6.C++11 chrono库,微秒级别计时器
auto start = steady_clock::now();Sleep(1000);auto end = steady_clock::now();auto last = duration_cast<microseconds>(end - start);cout << last.count() << "um";
需要包含头文件 #include <chrono>并且using namespace std::chrono;