😸

[C] times 関数

に公開

機能

プログラム実行時間やCPU使用時間などの計測を行うPOSIX標準の関数[1]

使用例

リアルタイム, ユーザCPU時間, システムCPU時間 を取得して表示する

\n は改行を表す エスケープシーケンス[2]

コード

#include <sys/times.h>
#include <stdio.h>
#include <unistd.h>

struct tms t;
clock_t start = times(&t);
/* 任意の処理 */
clock_t end = times(&t);

printf("Real time: %ld\n", end - start);
printf("User CPU time: %ld\n", t.tms_utime);
printf("System CPU time: %ld\n", t.tms_stime);
全文
#include <stdio.h>
#include <sys/times.h>
#include <unistd.h>

int main() {
    struct tms t;
    clock_t start = times(&t);

    for(int i = 0; i < 1000000; i++); // ダミーループ

    clock_t end = times(&t);

    printf("Real time: %ld\n", end - start);
    printf("User CPU time: %ld\n", t.tms_utime);
    printf("System CPU time: %ld\n", t.tms_stime);
    return 0;
}

実行結果

Real time: 4
User CPU time: 2
System CPU time: 0

時刻差 を変数から計算して表示する

コード

#include <sys/times.h>
#include <stdio.h>
#include <unistd.h>

struct tms t1, t2;
clock_t s = times(&t1);
/* 任意の処理 */
clock_t e = times(&t2);

printf("User: %ld\n", t2.tms_utime - t1.tms_utime);
printf("Sys : %ld\n", t2.tms_stime - t1.tms_stime);
全文
#include <stdio.h>
#include <sys/times.h>
#include <unistd.h>

int main() {
    struct tms t1, t2;
    clock_t s = times(&t1);

    for(int i = 0; i < 1000000; i++); // 何らかの処理

    clock_t e = times(&t2);

    printf("User: %ld\n", t2.tms_utime - t1.tms_utime);
    printf("Sys : %ld\n", t2.tms_stime - t1.tms_stime);
    return 0;
}

実行結果

User: 2
Sys : 0
脚注
  1. timesはプロセスの実行時間やCPU利用時間などの情報を取得するPOSIX標準関数。Windowsなど一部環境では利用不可。 ↩︎

  2. 改行やタブなど、画面に表示されない制御文字のこと。 ↩︎

Discussion