如何获得与系统时间无关的时差(毫秒)?

Pau*_*mon 3 c++ linux

我需要在Linux上计算时间差(毫秒)(Ubuntu 14).

它需要独立于系统时间,因为应用程序可能在执行期间更改它(它根据从GPS接收的数据设置系统时间).

我检查了时钟功能,它对我们不起作用,因为它返回程序消耗的处理器时间,我们需要实时.

sysinfo(如本问题中所述)自启动后返回秒数,同样,我们需要几毫秒.

根据我们的测试,从/ proc/uptime读取(如本问题中所述)似乎很慢(考虑到我们需要毫秒并重复调用此函数).

我们可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

时钟:

(无效,返回应用程序使用的刻度,而不是实时)

#include <time.h>
unsigned int GetMs(){
    unsigned int ret = 0;
    clock_t t;
    t = clock();
    ret = t / 1000;
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

运行时间:

#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);
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

  • gettimeofday:31毫秒
  • 时钟:153毫秒
  • 正常运行时间:6005毫秒

Nat*_*ica 9

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

std::chrono::steady_clock代表单调时钟.物理时间向前移动时,此时钟的时间点不会减少.此时钟与挂钟时间无关(例如,它可能是自上次重启后的时间),并且最适合测量间隔.

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