Home >Backend Development >C++ >How to Implement a Cross-Platform High-Resolution Timer in C ?

How to Implement a Cross-Platform High-Resolution Timer in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-13 02:39:10457browse

How to Implement a Cross-Platform High-Resolution Timer in C  ?

Cross-Platform High-Resolution Timer in C

Implementing a simple timer mechanism in C that works on both Windows and Linux with millisecond accuracy is a common task. To address this, C 11 introduces , which provides cross-platform support for high-resolution timers. Here's how you can achieve this:

Using :

#include <iostream>
#include <chrono>
#include "chrono_io"  // For ease of I/O

int main() {
  typedef std::chrono::high_resolution_clock Clock;
  auto t1 = Clock::now();
  auto t2 = Clock::now();
  std::cout << t2 - t1 << '\n';
}

Improved Precision with Workaround:

However, if you encounter high latency in subsequent calls to std::chrono::high_resolution_clock (as observed on VS11), a workaround exists that utilizes inline assembly and hardwires the machine's clock speed.

Custom Implementation (Intel-Specific):

#include <chrono>

struct clock {
  typedef unsigned long long rep;
  typedef std::ratio<1, 2800000000> period;  // Machine-specific clock speed
  typedef std::chrono::duration<rep, period> duration;
  typedef std::chrono::time_point<clock> time_point;
  static const bool is_steady = true;

  static time_point now() noexcept {
    unsigned lo, hi;
    asm volatile("rdtsc" : "=a"(lo), "=d"(hi));
    return time_point(duration(static_cast<rep>(hi) << 32 | lo));
  }

  static bool check_invariants() {
    static_assert(1 == period::num, "period must be 1/freq");
    static_assert(std::is_same<rep, duration::rep>::value,
                  "rep and duration::rep must be the same type");
    static_assert(std::is_same<period, duration::period>::value,
                  "period and duration::period must be the same type");
    static_assert(std::is_same<duration, time_point::duration>::value,
                  "duration and time_point::duration must be the same type");
    return true;
  }

  static const bool invariants = check_invariants();
};

Using the Custom :

using std::chrono::nanoseconds;
using std::chrono::duration_cast;
auto t0 = clock::now();
auto t1 = clock::now();
nanoseconds ns = duration_cast<nanoseconds>(t1 - t0);

The above is the detailed content of How to Implement a Cross-Platform High-Resolution Timer in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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