Home > Backend Development > C++ > How to Achieve High-Precision Timing in C on Linux?

How to Achieve High-Precision Timing in C on Linux?

DDD
Release: 2024-11-09 17:20:02
Original
1055 people have browsed it

How to Achieve High-Precision Timing in C   on Linux?

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:

  • Boost ptime: A Boost library function that returns nanosecond-precision timestamps.
  • POSIX clock_gettime(): A system call that provides timestamps with varying precision based on the specified clock type. For example, CLOCK_MONOTONIC provides a high-resolution, monotonically increasing timestamp.

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template