高分辨率计时器
来源:互联网 发布:凡科建站如何绑定域名 编辑:程序博客网 时间:2024/05/16 05:44
原文地址:http://www.songho.ca/misc/timer/timer.html
下载:timer.zip
C标准库提供函数clock()来测量执行时间。它是一个声明在time.h(大多数系统兼容)中的系统独立函数,但是它不能给出精确的结果,甚至毫秒级精度都不可以。
为了测试clock()的精度,请在你的机器上执行下方的代码。代码输出告诉我们函数clock()可以检测到的最小时钟差别。我在我的系统上得到15ms的精度。
#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()测量执行时间的用法。
#include <iostream>#include <windows.h> // for Windows APIsusing 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()之前包含这个头文件。它也给出微妙级的测量。这里是一个代码片段。
#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
下面的代码给出了基本的用法。
#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
- 高分辨率计时器
- 高分辨率计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 计时器
- 72岁老人获计算机专业博士 60岁考研比博导大1岁
- Spring中添加定时任务 JOB
- oracle 11g clusterware学习笔记
- 身在职场 不得不知的二十三条职场语录
- VIM操作
- 高分辨率计时器
- 【OpenCV】Canny 边缘检测
- 种类为两种时,并查集的解题应用poj1703和hdu1829
- Mate(三)——常见问题
- java1.5新特性
- ubuntu下修改目录的权限
- 关于跨平台移动应用开发框架的探索 -- PhoneGap
- SSL 与 数字证书 的基本概念和工作原理
- 使用Eclipse构建Maven的SpringMVC项目(一)