我想用C来测量时间,我很难弄明白,我想要的是这样的东西:
- 启动计时器
- 运行一个方法
- 停止计时
- 报告所用时间(至少达到微精度)
任何帮助都将不胜感激.
(我正在windows中使用mingw进行编译)
我想用C来测量时间,我很难弄明白,我想要的是这样的东西:
任何帮助都将不胜感激.
(我正在windows中使用mingw进行编译)
提供1微秒分辨率的高分辨率计时器是特定于系统的,因此您必须在不同的操作系统平台上使用不同的方法来实现这一点.您可能感兴趣的是判断下面的文章,它基于以下函数实现跨平台C++计时器类:
Windows
Windows API提供了极高分辨率的计时器函数:QueryPerformanceCounter()
,返回当前经过的滴答声;QueryPerformanceFrequency()
,返回每秒滴答声的数量.
例子:
#include <stdio.h>
#include <windows.h> // for Windows APIs
int main(void)
{
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;
printf("%f ms.\n", elapsedTime);
}
Linux, Unix, and Mac
对于基于Unix或Linux的系统,您可以使用gettimeofday()
.此函数在"sys/time.h"中声明.
例子:
#include <stdio.h>
#include <sys/time.h> // for gettimeofday()
int main(void)
{
struct 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
printf("%f ms.\n", elapsedTime);
}