我需要在Linux(Ubuntu 14)上计算毫秒级的时间差。
这个时间差需要独立于系统时间,因为应用程序在执行过程中可能会更改它(根据从GPS接收到的数据设置系统时间)。
我已经检查了clock函数,但它对我们来说不起作用,因为它返回程序消耗的处理器时间,而我们需要真实时间。
sysinfo(如此问题中所述)返回自启动以来的秒数,而我们需要毫秒。
并且从/proc/uptime中读取(如此问题中所述)根据我们的测试似乎很慢(考虑到我们想要毫秒级别,而且这个函数被重复调用)。
我们可以使用C++11,但我认为std::chrono也与系统时间有关(如果我错了,请纠正我)。
还有其他方法可以完成这个任务吗?
我们的性能测试(用于比较/ proc / uptime),100万次重复调用:
gettimeofday:
(不是我们需要的,因为它取决于系统时间)
#include <sys/time.h>
unsigned int GetMs(){
unsigned int ret = 0;
timeval ts;
gettimeofday(&ts,0);
static long long inici = 0;
if (inici==0){
inici = ts.tv_sec;
}
ts.tv_sec -= inici;
ret = (ts.tv_sec*1000 + (ts.tv_usec/1000));
return ret;
}
时钟:
(无效,返回应用程序使用的滴答数,而非实际时间)
#include <time.h>
unsigned int GetMs(){
unsigned int ret = 0;
clock_t t;
t = clock();
ret = t / 1000;
return ret;
}
运行时间:
#include <fstream>
unsigned int GetMs(){
unsigned int ret = 0;
double uptime_seconds;
if (std::ifstream("/proc/uptime", std::ios::in) >> uptime_seconds) {
ret = (int) (1000 * uptime_seconds);
}
}
结果:
- gettimeofday:31 毫秒
- clock:153 毫秒
- uptime:6005 毫秒