#include <time.h> int clock_gettime(clockid_t clk_id, struct timespec *tp);を使用する。
timespec の構造体は以下の通り定義されている。
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
#include <time.h> int clock_gettime(clockid_t clk_id, struct timespec *tp);を使用する。
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
#include <stdio.h>
#include <time.h>
#include <unistd.h>
int main(){
struct timespec res,tp1,tp2;
long sec,nsec;
// 時刻精度の確認
if(clock_getres(CLOCK_REALTIME,&res) < 0){
perror("clock_getres");
return 1;
}
printf("Time Precision:\t%ld.%09ld\n", (long)res.tv_sec, res.tv_nsec);
if(clock_gettime(CLOCK_REALTIME,&tp1) < 0){
perror("clock_gettime begin");
return 2;
}
// 処理時間を計測したいコードをここに記述
// 開始
usleep(100000);
// 終了
if(clock_gettime(CLOCK_REALTIME,&tp2) < 0){
perror("clock_gettime end");
return 3;
}
sec = tp2.tv_sec - tp1.tv_sec;
nsec = tp2.tv_nsec - tp1.tv_nsec;
if(nsec < 0){
sec--;
nsec += 1000000000L;
}
printf("Time Span:\t%ld.%09ld\n",sec,nsec);
return 0;
}
$ gcc -O2 -Wall -g -o mytimespan -lrt mytimespan.c
$ ./mytimespan Time Precision: 0.000000001 Time Span: 0.100170659