LoginSignup
0
0

More than 1 year has passed since last update.

rdtsc関数によるクロックサイクル数計測

Last updated at Posted at 2022-01-14

はじめに

C言語でプログラムを作った際にクロックサイクル数で時間の計測をしなければならない状況になりました。
が、秒単位で計測時間を出すやり方は溢れているのにクロックサイクル数で出すやり方はあまり出てこなかったので、今後の備忘録とするために作りました。

読んで欲しい人

  • C言語でクロックサイクル数の計測をしたい人

環境

  • Ubuntu 18.04.2 LTS (GNU/Linux 5.4.0-91-generic x86_64)
  • Windows10 Visual Studio

使い方1. Ubuntu

アセンブリに埋め込むコードを記述します。
環境によって違うと思われますが、今回はx86_64環境なのでヘッダファイルx86intrin.hをインストールします。(1/24修正)

extern uint64_t cycle;
void func()
{
  // 計測したい処理
}
void main()
{
  uint64_t ts0,ts1;
  ts0 = __rdtsc();
  func();
  ts1 = __rdtsc();
  cycle = ts1 - ts0;
}

func()の部分を計測できます。

使い方2. Visual Studio

ヘッダファイルintrin.hをインクルードします。

#include <intrin.h>

unsigned long long cycle;
void func()
{
  // 計測したい処理
}

void main()
{
  unsigned long long ts0,ts1;
  ts0 = __rdtsc();
  func();
  ts1 = __rdtsc();
  cycle = ts1 - ts0;
}

func()の部分を計測できます。

おわりに

間違い等ありましたらコメントいただけると助かります。
(1/24: Ubuntuの方など修正)

参考文献

[1][__rdtsc | Microsoft Docs]
https://docs.microsoft.com/ja-jp/cpp/intrinsics/rdtsc?view=msvc-170
[2][CPUクロックに基づく相対時刻の計測]
http://www.02.246.ne.jp/~torutk/cxx/clock/cpucounter.html
[3][高性能プログラミング(Ⅱ)上級編]
https://www.cc.u-tokyo.ac.jp/public/VOL10/No5/200809tuning.pdf

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0