纳秒时间戳基准测试:std::chrono vs clock_gettime(CLOCK_REALTIME)
在 C/C++ 中,有两种基本的纳秒分辨率时间戳方法:
方法 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();
}此方法只需要 C++11 和 C++ 标准库。它是可移植的,适用于所有支持 C++11 的平台。
方法 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;
}此方法在 POSIX 兼容系统上可用,不可移植到 Windows。
基准测试
请参阅下面的完整代码以对两种方法进行基准测试。
结果
在 Intel(R) Core(TM) i7-14700、Ubuntu 内核 6.8.1-1018-realtime 和 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换句话说:
- 两种方法都非常快,
clock_gettime稍快。 - 尽管
std::chrono方法看起来进行了更复杂的函数调用,但这些似乎被编译器优化掉了。 - 性能差异可以忽略不计,两种方法都适用于高分辨率时间戳。
完整基准测试代码
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
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow