我想用C测量时间,我很难搞清楚,我想要的是这样的:
任何帮助,将不胜感激.
(我使用mingw在windows中编译)
Dan*_*llo 97
提供1微秒分辨率的高分辨率计时器是系统特定的,因此您必须使用不同的方法在不同的OS平台上实现此目的.您可能有兴趣查看以下文章,该文章基于下面描述的函数实现了跨平台C++计时器类:
视窗
Windows API提供了极高分辨率的计时器功能:QueryPerformanceCounter()它返回当前经过的刻度,并QueryPerformanceFrequency()返回每秒的刻度数.
例:
#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;
}
Run Code Online (Sandbox Code Playgroud)
Linux,Unix和Mac
对于基于Unix或Linux的系统,您可以使用gettimeofday().该函数在"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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,上面的示例需要使用C++编译,mingw支持.
Pau*_*l R 18
在Linux上,您可以使用clock_gettime():
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // get initial time-stamp
// ... do stuff ... //
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // get final time-stamp
double t_ns = (double)(end.tv_sec - start.tv_sec) * 1.0e9 +
(double)(end.tv_nsec - start.tv_nsec);
// subtract time-stamps and
// multiply to get elapsed
// time in ns
Run Code Online (Sandbox Code Playgroud)