我需要在 Linux (Ubuntu 14) 上计算以毫秒为单位的时差。
它需要独立于系统时间,因为应用程序可能会在执行过程中更改它(它根据从 GPS 接收到的数据设置系统时间)。
我检查了 clock函数,它对我们不起作用,因为它返回程序消耗的处理器时间,而我们需要实时。
系统信息(如本 question 中所述)返回启动后的秒数,同样,我们需要毫秒数。
根据我们的测试,从/proc/uptime 读取(如本 question 中所述)似乎很慢(考虑到我们需要毫秒并且此函数被重复调用)。
我们可以使用 C++11,但我认为 std::chrono 也与系统时间相关(如果我错了请纠正我)。
还有其他方法可以实现吗?
我们的性能测试(用于/proc/uptime 比较),100 万次重复调用:
获取时间:
(不是我们需要的,因为它取决于系统时间)
#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 毫秒
最佳答案
Class
std::chrono::steady_clock
represents a monotonic clock. The time points of this clock cannot decrease as physical time moves forward. This clock is not related to wall clock time (for example, it can be time since last reboot), and is most suitable for measuring intervals.
如果您需要支持 C++98/03 环境,您也可以使用 boost:steady_clock
关于c++ - 如何获得独立于系统时间的时间差(毫秒)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44826891/