[英]C++ timer in microseconds
I am trying to do a timer in microseconds, but it's not quite working. 我正在尝试以微秒为单位做一个计时器,但效果不佳。
#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;
}
The result look like this: 结果看起来像这样:
START: 3586
END: 3630
DIFF: 43
I need the DIFF be around 5000. Any suggestions? 我需要的DIFF在5000左右。有什么建议吗?
I'm not sure what you're trying to measure, but I guess CLOCK_PROCESS_CPUTIME_ID
is the wrong timer, you likely want CLOCK_MONOTONIC
if you want to measure some elapsed time. 我不确定您要测量的是什么,但是我想
CLOCK_PROCESS_CPUTIME_ID
是错误的计时器,如果要测量经过的时间,则可能需要CLOCK_MONOTONIC
。 Have a look at a similar stackoverflow question that shows the difference between the different clocks of clock_gettime
. 看一下类似的stackoverflow问题 ,该问题显示
clock_gettime
的不同时钟之间的差异。
That said, to get the full time you have to add tv_sec
and tv_nsec
(of course first converting tv_sec
to nano seconds) of each measurement and then subtract that total, so something like: 就是说,要获得全部时间,您必须将每个测量的
tv_sec
和tv_nsec
(当然,首先将tv_sec
转换为纳秒),然后减去该总计,所以类似:
uint64_t startNs = start_time.tv_sec * 1000 * 1000 * 1000 + start_time.tv_nsec;
uint64_t endNs = end_time.tv_sec * 1000 * 1000 * 1000 + end_time.tv_nsec;
uint64_t diffNs = endNs - startNs;
uint64_t diffMicro = diffNs / 1000;
And if you're on C++11, probably best use some high level class from the chrono namespace. 而且,如果您使用的是C ++ 11,则最好使用chrono名称空间中的一些高级类 。
Two things. 两件事情。
timespec
- need to take both into account when doing the subtraction timespec
有两个组成部分-进行减法时需要将两者都考虑在内 try with clock_gettime( CLOCK_REALTIME, &start) clock_gettime( CLOCK_REALTIME, &stop) 尝试使用clock_gettime(CLOCK_REALTIME,&start)clock_gettime(CLOCK_REALTIME,&stop)
You need to use 'tv_sec' part of the timespec structure as well. 您还需要使用timespec结构的“ tv_sec”部分。
Time = ((stop.tv_sec - start.tv_sec)+ (double)(stop.tv_nsec - start.tv_nsec)/1e9)*1000;//im ms 时间=((stop.tv_sec-start.tv_sec)+(double)(stop.tv_nsec-start.tv_nsec)/ 1e9)* 1000; // im ms
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.