【发布时间】:2014-04-20 18:36:57
【问题描述】:
我试图在微秒内做一个计时器,但它不太有效。
#include <time.h>
#include <iostream>
#include <unistd.h>
using namespace std;
int main ()
{
struct timespec start_time;
struct timespec end_time;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
usleep(5000);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
cout << "START: " << (start_time.tv_nsec/1000) << endl;
cout << "END: " << (end_time.tv_nsec/1000) << endl;
cout << "DIFF: " << (end_time.tv_nsec - start_time.tv_nsec) /1000 << endl;
return 0;
}
结果如下:
START: 3586
END: 3630
DIFF: 43
我需要 DIFF 在 5000 左右。有什么建议吗?
【问题讨论】:
-
有一个标准的
<chrono>标头。不需要特定于平台的代码。 -
@chris:不过,仅从 C++11 开始。