クロックを用いた時間計測のライブラリを作りました。
サポート対象
C言語規格
- C11
コンパイラ
- Clang
- GCC
OS
- Linux
- macOS
あとは知らん
ロジック
- Clang の時は
__builtin_readcyclecounter()
を用いる - GCC でかつ x86 アーキテクチャの時には,
__rdtsc()
を用いる - 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 についても下記を参考にクロックを読み取る命令のコードに書き換えたい。