我需要计算Linux(Ubuntu 14)上的时间差(以毫秒为单位)。如何获得独立于系统时间的时间差异(毫秒)?
它需要独立于系统时间,因为应用程序可能会在执行期间更改它(它会根据从GPS接收的数据设置系统时间)。
我检查了clock函数,它不适用于我们,因为它返回程序消耗的处理器时间,我们需要实时。
sysinfo(如在此question中所述)会在启动后返回秒数,并且我们还需要几毫秒。
根据我们的测试(考虑到我们需要毫秒,并且此函数被重复调用),从/ proc/uptime(在此question中提到)读取似乎很慢。
我们可以使用C++ 11,但我认为std :: chrono也与系统时间有关(如果我错了,请纠正我)。
有没有其他的方法来完成这个?
我们的性能测试(用于的/ proc /运行时间比较),重复调用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毫秒
感谢您的回答。它完美地工作,并不依赖于系统时钟,这符合我的要求。然而,根据我的测试,我接受@ zwol的答案是更快。在我的嵌入式设备上,有1000000次重复调用,std :: chrono :: steady_clock花了3523 ms,clock_gettime和CLOCK_MONOTONIC花了2184 ms。 –
@PauGuillamon没问题。乐意效劳。 – NathanOliver