Luzhiled's Library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub ei1333/library

:warning: Timer(タイマー) (other/timer.hpp)

概要

rdtsc (Read Time Stamp Counter) 命令を用いると CPU クロックごとに加算される 64 bit のタイムスタンプカウンタの値を得ることができる. マラソンするときにタイマーとしてよく用いられるらしい.

CPUのクロック周波数がわかれば, カウンタの値から実行時間を推定することができる. 参考までにAtCoder では 3.00GHz, Codeforces では 3.60GHz, yukicoder では 2.3GHz (2020/06/30現在).

ベンチマーク

$10^8$ 回呼び出したときの実行時間の比較. 間違っていたらごめんなさい.

AtCoder:

Codeforces:

yukicoder:

Code

/**
 * @brief Timer(タイマー)
 *
 */
constexpr uint64_t CYCLES_PER_SEC = 3000000000;  // AtCoder
// constexpr uint64_t CYCLES_PER_SEC = 3600000000; // Codeforces
// constexpr uint64_t CYCLES_PER_SEC = 2300000000; // yukicoder
struct Timer {
  uint64_t start;

  Timer() : start{} { reset(); }

  void reset() { start = get_cycle(); }

  inline double get_second() const {
    return (double)get_cycle() / CYCLES_PER_SEC;
  }

  inline uint64_t get_cycle() const {
    unsigned low, high;
    __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
    return (((uint64_t)low) | ((uint64_t)high << 32ull)) - start;
  }
};
#line 1 "other/timer.hpp"
/**
 * @brief Timer(タイマー)
 *
 */
constexpr uint64_t CYCLES_PER_SEC = 3000000000;  // AtCoder
// constexpr uint64_t CYCLES_PER_SEC = 3600000000; // Codeforces
// constexpr uint64_t CYCLES_PER_SEC = 2300000000; // yukicoder
struct Timer {
  uint64_t start;

  Timer() : start{} { reset(); }

  void reset() { start = get_cycle(); }

  inline double get_second() const {
    return (double)get_cycle() / CYCLES_PER_SEC;
  }

  inline uint64_t get_cycle() const {
    unsigned low, high;
    __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
    return (((uint64_t)low) | ((uint64_t)high << 32ull)) - start;
  }
};
Back to top page