【发布时间】:2017-06-29 13:43:43
【问题描述】:
我需要在 Linux (Ubuntu 14) 上以毫秒为单位计算时间差。
它需要独立于系统时间,因为应用程序可能会在执行过程中更改它(它根据从 GPS 接收到的数据设置系统时间)。
我检查了clock 函数,它对我们不起作用,因为它返回程序消耗的处理器时间,我们需要实时。
sysinfo(如 question 中提到的)返回自启动以来的秒数,同样,我们需要毫秒数。
根据我们的测试,从 /proc/uptime(如 question 中提到的)读取似乎很慢(考虑到我们需要毫秒并且重复调用此函数)。
我们可以使用 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 毫秒
- 时钟:153 毫秒
- 正常运行时间:6005 毫秒
【问题讨论】: