LoginSignup
2
2

More than 3 years have passed since last update.

クロックを用いた時間計測

Last updated at Posted at 2020-05-06

クロックを用いた時間計測のライブラリを作りました。

サポート対象

C言語規格

  • C11

コンパイラ

  • Clang
  • GCC

OS

  • Linux
  • macOS

あとは知らん

ロジック

  1. Clang の時は __builtin_readcyclecounter() を用いる
  2. GCC でかつ x86 アーキテクチャの時には,__rdtsc() を用いる
  3. GCC でかつ Linux の時には,timespec_get() を用いる

あとは知らん

ソースコード

clockcycle.h
#ifndef CLOCKCYCLE_H
#define CLOCKCYCLE_H

#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

#ifdef __clang__
static inline uint64_t now() {
    return __builtin_readcyclecounter();
}
#elif defined(__GNUC__)
#if defined(__i386__) || defined(__x86_64__) || defined(__amd64__)
#include <x86intrin.h>
static inline uint64_t now() {
    return __rdtsc();
}
#elif defined(__linux__)
#include <time.h>
static inline uint64_t now() {
    struct timespec ts = {0, 0};
    timespec_get(&ts, TIME_UTC);
    return (uint64_t)(ts.tv_sec) * 1000000000 + ts.tv_nsec;
}
#else
#error unsupported architecture
#endif
#endif

#ifdef __cplusplus
}
#endif // __cplusplus

#endif // CLOCKCYCLE_H

おわりに

本当は ARM についても下記を参考にクロックを読み取る命令のコードに書き換えたい。

2
2
1

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
2
2