如何测量C中的时间间隔? [英] How do I measure a time interval in C?
问题描述
我想用 C 来测量时间,但我很难弄清楚,我想要的是这样的:
I would like to measure time in C, and I am having a tough time figuring it out, all I want is something like this:
- 启动计时器
- 运行一个方法
- 停止计时器
- 报告花费的时间(至少要精确到微量级)
任何帮助将不胜感激.
(我正在使用 mingw 在 windows 中编译)
(I am compiling in windows using mingw)
推荐答案
提供 1 微秒分辨率的高分辨率计时器是特定于系统的,因此您必须使用不同的方法在不同的操作系统平台上实现这一点.您可能有兴趣查看以下文章,该文章基于以下描述的函数实现了一个跨平台的 C++ 计时器类:
High resolution timers that provide a resolution of 1 microsecond are system-specific, so you will have to use different methods to achieve this on different OS platforms. You may be interested in checking out the following article, which implements a cross-platform C++ timer class based on the functions described below:
- [Song Ho Ahn - 高分辨率计时器][1]
Windows
Windows API 提供了极高分辨率的计时器函数:QueryPerformanceCounter()
,它返回当前经过的滴答声,以及 QueryPerformanceFrequency()
,它返回每个滴答声的数量第二个.
The Windows API provides extremely high resolution timer functions: QueryPerformanceCounter()
, which returns the current elapsed ticks, and QueryPerformanceFrequency()
, which returns the number of ticks per second.
示例:
#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.
", elapsedTime);
}
Linux、Unix 和 Mac
对于基于 Unix 或 Linux 的系统,您可以使用 gettimeofday()
.该函数在sys/time.h"中声明.
For Unix or Linux based system, you can use gettimeofday()
. This function is declared in "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.
", elapsedTime);
}
这篇关于如何测量C中的时间间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!