2017-06-29 42 views
1

我需要计算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毫秒

回答

3

低层系统原始,你想要做什么是clock_gettimeCLOCK_MONOTONIC“clockid”。

CLOCK_MONOTONIC:时钟不能被集合并且表示,因为一些不确定的起点单调时间。此时钟不受系统时间内不连续跳转的影响(例如系统管理员手动更改时钟),但会受到由adjtime(3)和NTP执行的增量调整的影响。

(即“受受的adjtime进行增量调整(3)和NTP”几乎可以肯定,你想要的东西。)

此功能在<time.h>声明,并与GNU libc中的当前版本,可以默认访问。对于旧版本,您可能需要将_POSIX_C_SOURCE定义为大于或等于200809L的值,然后才包括任何系统标题(不仅在包括time.h之前),并且您可能还需要将程序与-lrt关联。

clock_gettime返回struct timespec,它可以表示单纳秒的差异;实际精度通常稍低一些,但是您应该能够依靠毫秒级精度进行计算,尤其是在“训练”系统时钟的程序(例如ntpd)正在运行时。

7

你想要的是std::chrono::steady_clock

std::chrono::steady_clock表示单调时钟。这个时钟的时间点不能随着物理时间的推移而减少。此时钟与挂钟时间无关(例如,可能是自上次重新启动以来的时间),并且最适合测量间隔。

如果您需要支持C++ 98/03环境中,你也可以使用boost:steady_clock

+0

感谢您的回答。它完美地工作,并不依赖于系统时钟,这符合我的要求。然而,根据我的测试,我接受@ zwol的答案是更快。在我的嵌入式设备上,有1000000次重复调用,std :: chrono :: steady_clock花了3523 ms,clock_gettime和CLOCK_MONOTONIC花了2184 ms。 –

+0

@PauGuillamon没问题。乐意效劳。 – NathanOliver

相关问题