Benchmark de timestamping nanosegundo: std::chrono vs clock_gettime(CLOCK_REALTIME)

Em C/C++ existem dois métodos essenciais de timestamping com resolução de nanosegundos:

Método A: std::chrono::high_resolution_clock

benchmark_nanosecond_timestamping.cpp
uint64_t getCurrentNanoTimestampCpp() {
    return std::chrono::duration_cast<std::chrono::nanoseconds>(
        std::chrono::high_resolution_clock::now().time_since_epoch()
    ).count();
}

Este método apenas requer C++11 e a biblioteca padrão C++. É portável e funciona em todas as plataformas que suportam C++11.

Método B: clock_gettime(CLOCK_REALTIME)

get_current_nanotime_c.cpp
#include <ctime>

uint64_t getCurrentNanoTimestampC() {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    return (uint64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}

Este método está disponível em sistemas compatíveis com POSIX e não é portável para Windows.

Benchmark

Veja abaixo o código completo para fazer benchmark dos dois métodos.

Resultados

Resultados em Intel(R) Core(TM) i7-14700, Ubuntu com kernel 6.8.1-1018-realtime e g++ -fexpensive-optimizations -O3 -march=native -o benchmark_nanosecond_timestamping benchmark_nanosecond_timestamping.cpp

benchmark_results.txt
C clock_gettime average time per call: 13.603 ns
C++ chrono average time per call: 14.1544 ns

Em outras palavras:

  • Ambos os métodos são extremamente rápidos, com clock_gettime sendo ligeiramente mais rápido.
  • Embora o método std::chrono pareça fazer chamadas de função mais complexas, estas parecem ser otimizadas pelo compilador.
  • A diferença de desempenho é negligenciável, e ambos os métodos são adequados para timestamping de alta resolução.

Código completo de benchmark

benchmark_nanosecond_timestamping_full.cpp
#include <iostream>
#include <chrono>
#include <ctime>

uint64_t getCurrentNanoTimestampC() {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    return (uint64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}

uint64_t getCurrentNanoTimestampCpp() {
    return std::chrono::duration_cast<std::chrono::nanoseconds>(
        std::chrono::system_clock::now().time_since_epoch()
    ).count();
}

void benchmarkFunction(uint64_t (*func)(), const std::string& name, int iterations) {
    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < iterations; ++i) {
        func();
    }
    auto end = std::chrono::high_resolution_clock::now();

    std::chrono::duration<double, std::nano> duration = end - start;
    std::cout << name << " average time per call: "
              << (duration.count() / iterations) << " ns" << std::endl;
}

int main() {
    constexpr int iterations = 10000000;

    benchmarkFunction(getCurrentNanoTimestampC, "C clock_gettime", iterations);
    benchmarkFunction(getCurrentNanoTimestampCpp, "C++ chrono", iterations);

    return 0;
}

Check out similar posts by category: C/C++ Performance Benchmarks