From 58a44db0c5c23d1c1c613b1b5ed530ebfd8c7c78 Mon Sep 17 00:00:00 2001 From: Andrew Belt Date: Tue, 17 Dec 2019 19:20:22 -0500 Subject: [PATCH] Slightly increase performance of system::getNanoseconds() for Linux. --- include/system.hpp | 5 +++-- src/system.cpp | 9 ++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/include/system.hpp b/include/system.hpp index 36fe7b08..8731d74a 100644 --- a/include/system.hpp +++ b/include/system.hpp @@ -36,8 +36,9 @@ int getLogicalCoreCount(); void setThreadName(const std::string& name); /** Returns the caller's human-readable stack trace with "\n"-separated lines. */ std::string getStackTrace(); -/** Returns the current number of nanoseconds since the epoch with the highest precion available on the OS. -The epoch is undefined and could be the UNIX epoch, time since boot, time since launch, etc. +/** Returns the current number of nanoseconds since the epoch. +The goal of this function is to give the most precise (fine-grained) time available on the OS for benchmarking purposes, while being fast to compute. +The epoch is undefined. Do not use this function to get absolute time, as it is different on each OS. */ int64_t getNanoseconds(); /** Opens a URL, also happens to work with PDFs and folders. diff --git a/src/system.cpp b/src/system.cpp index b6aec55c..f912826a 100644 --- a/src/system.cpp +++ b/src/system.cpp @@ -225,7 +225,14 @@ int64_t getNanoseconds() { int64_t nsPerTick = 1000000000LL / frequency.QuadPart; int64_t time = counter.QuadPart * nsPerTick; return time; -#else +#endif +#if defined ARCH_LIN + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + int64_t time = int64_t(ts.tv_sec) * 1000000000LL + ts.tv_nsec; + return time; +#endif +#if defined ARCH_MAC using clock = std::chrono::high_resolution_clock; using time_point = std::chrono::time_point; time_point now = clock::now();