我是靠谱客的博主 秀丽绿草,这篇文章主要介绍高分辨率计时器,现在分享给大家,希望可以做个参考。

原文地址:http://www.songho.ca/misc/timer/timer.html

下载:timer.zip


C标准库提供函数clock()来测量执行时间。它是一个声明在time.h(大多数系统兼容)中的系统独立函数,但是它不能给出精确的结果,甚至毫秒级精度都不可以。
为了测试clock()的精度,请在你的机器上执行下方的代码。代码输出告诉我们函数clock()可以检测到的最小时钟差别。我在我的系统上得到15ms的精度。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream> #include <ctime> using namespace std; int main() { clock_t t1, t2; t1 = t2 = clock(); // loop until t2 gets a different value while(t1 == t2) t2 = clock(); // print resolution of clock() cout << (double)(t2 - t1) / CLOCKS_PER_SEC * 1000 << " ms.n"; return 0; }

因此我们需要一个高精度的计时器至少在1ms的精度上测量执行时间。好消息是有这样的高精度定时器函数,坏消息是他们是系统相关的。换句话说,你必须在在不同的系统上编写不同的代码。windows 提供函数QueryPerformanceCounter(),而Unix、Linux和Mac OS X系统有函数gettimeofday(),它声明在sys/time.h中。两个函数可以测量至少微妙级的差别。

Windows
Windows API提供了一组极精确的计时器函数,QueryPerformanceCounter()和QueryPerformanceFrequency()。QueryPerformanceCounter()被用于得到当前的时间片。
QueryPerformanceFrequency()被用于得到每秒的时间片数量,这样可以将时间片转化成精确的时间。
这里是QueryPerformanceCounter()测量执行时间的用法。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream> #include <windows.h> // for Windows APIs using namespace std; int main() { LARGE_INTEGER frequency; // ticks per second LARGE_INTEGER t1, t2; // ticks double elapsedTime; // get ticks per second QueryPerformanceFrequency(&frequency); // start timer QueryPerformanceCounter(&t1); // do something ... // stop timer QueryPerformanceCounter(&t2); // compute and print the elapsed time in millisec elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart; cout << elapsedTime << " ms.n"; return 0; }

Unix,linux 和 Mac
gettimeofday() 可以被用于基于Unix或者Linux类的系统。这个函数被声明在“sys/time.h”中。因此你必须在使用gettimeofday()之前包含这个头文件。它也给出微妙级的测量。这里是一个代码片段。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream> #include <sys/time.h> // for gettimeofday() using namespace std; int main() { timeval t1, t2; double elapsedTime; // start timer gettimeofday(&t1, NULL); // do something ... // stop timer gettimeofday(&t2, NULL); // compute and print the elapsed time in millisec elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms cout << elapsedTime << " ms.n"; return 0; }

C++ Timer Class
这个计时器类将QueryPerformanceCounter()和gettimeofday()合并起来。因此它可以被使用在Unix/Linux/Mac和Windows系统中。它提供了一个简单的接口很容易地得到执行时间。
源代码可以再这里得到: timer.zip
下面的代码给出了基本的用法。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream> #include "Timer.h" using namespace std; int main() { Timer timer; // start timer timer.start(); // do something ... // stop timer timer.stop(); // print the elapsed time in millisec cout << timer.getElapsedTimeInMilliSec() << " ms.n"; return 0; }

原文地址:http://www.songho.ca/misc/timer/timer.html


最后

以上就是秀丽绿草最近收集整理的关于高分辨率计时器的全部内容,更多相关高分辨率计时器内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(105)

评论列表共有 0 条评论

立即
投稿
返回
顶部