用户 space (Linux) 中是否有任何高分辨率时钟 (us)?

Is there any high resolution clock (us) in User space (Linux)?

您是否知道 C/C++ 用户 space 中针对 Linux 的高分辨率时钟(最小微秒)的任何​​ C/C++ 实现(即使它不可移植)?

目标是测量一些低延迟操作经过的时间间隔。 我测量到内核-space 时钟有时会导致延迟尖峰。

根据我对 Red Hat 7.2 的研究:

谢谢。

一种选择是通过__builtin_ia32_rdtsc函数使用rdtsc指令。在现代 Intel CPUs rdtsc 中以任何 CPU 频率的基本时钟速率滴答,这样您就可以通过将计数器除以基数(而不是升压)将计数器转换为纳秒 CPU 以 GHz 为单位的频率:

#include <regex>
#include <string>
#include <fstream>
#include <iostream>

double cpu_base_frequency() {
    std::regex re("model name\s*:[^@]+@\s*([0-9.]+)\s*GHz");
    std::ifstream cpuinfo("/proc/cpuinfo");
    std::smatch m;
    for(std::string line; getline(cpuinfo, line);) {
        regex_match(line, m, re);
        if(m.size() == 2)
            return std::stod(m[1]);
    }
    return 1; // Couldn't determine the CPU base frequency. Just count TSC ticks.
}

double const CPU_GHZ_INV = 1 / cpu_base_frequency();

int main() {
    auto t0 = __builtin_ia32_rdtsc();
    auto t1 = __builtin_ia32_rdtsc();
    std::cout << (t1 - t0) * CPU_GHZ_INV << "nsec\n";
}

来自英特尔文档的更多信息:

Constant TSC behavior ensures that the duration of each clock tick is uniform and supports the use of the TSC as a wall clock timer even if the processor core changes frequency. This is the architectural behavior moving forward.

The invariant TSC will run at a constant rate in all ACPI P-, C- and T-states. This is the architectural behavior moving forward. On processors with invariant TSC support, the OS may use the TSC for wall clock timer services (instead of ACPI or HPET timers). TSC reads are much more efficient and do not incur the overhead associated with a ring transition or access to a platform resource.

The invariant TSC is based on the invariant timekeeping hardware (called Always Running Timer or ART), that runs at the core crystal clock frequency.

The scalable bus frequency is encoded in the bit field MSR_PLATFORM_INFO[15:8] and the nominal TSC frequency can be determined by multiplying this number by a bus speed of 100 MHz.

boost::timer has some interesting functions. I particularly like the auto timer。它以微秒为单位显示时间。不确定它是否可以低于此值。