High-Precision Timing in C on Linux
QueryPerformanceCounter from mmsystem.h provides a reliable high-resolution timer in Windows. For Linux, consider the following alternatives:
Code Example Using ptime:
#include <iostream> #include <boost/chrono/system_clocks.hpp> using namespace std; using namespace boost::chrono; int main() { auto now = system_clock::now(); nanoseconds ts = duration_cast<nanoseconds>(now - system_clock::from_time_t(0)); cout << "Timestamp: " << ts.count() << " nanoseconds" << endl; return 0; }
Code Example Using clock_gettime():
#include <iostream> #include <time.h> using namespace std; int main() { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); cout << "Timestamp: " << ts.tv_sec << " seconds, " << ts.tv_nsec << " nanoseconds" << endl; return 0; }
The above is the detailed content of How to Achieve High-Precision Timing in C on Linux?. For more information, please follow other related articles on the PHP Chinese website!