如何测量用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:
- 启动一个定时器
- 运行的方法
- 停止计时器
- 报告采取了(至少对微精度)时间
任何帮助将是AP preciated。
Any help would be appreciated.
(我编译使用MinGW的视窗)
(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 - High Resolution Timer
的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 <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;
}
的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 <iostream>
#include <sys/time.h> // for gettimeofday()
using namespace std;
int main()
{
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
cout << elapsedTime << " ms.\n";
return 0;
}
请注意,上述实施例需要用C ++,它的mingw 的载体
这篇关于如何测量用C的时间间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!