ホームに戻る
出典 :
関連 :
目次 :
C言語における時間の取り扱い
日時を取り扱うための関数およびデータ型が time.h に定義されている。
clock() と clock_t
clock() 関数は、そのプログラムが起動してからのプロセッサ時間を返却する。割り込みの処理中は計時されない。
戻り値は clock_t 型で、単位(精度)は環境によって異なる。値は名称に反し、クロック数とは一致しない。
尚、1秒あたりの clock_t の値が定数 CLOCKS_PER_SEC で定義されており、除算によって秒数を得ることができる。
#include <stdio.h>
#include <time.h>
void main(void)
{
clock_t start, end;
printf("Enterキーを押下してください。\n");
// メッセージ表示時点の clock_t 値
start = clock();
// Enterキーが押されるのを待つ
getchar();
// Enterキーが押された時点の clock_t 値
end = clock();
// 経過時間を秒数に変換
printf("%f秒でした。", (double)(end - start) / CLOCKS_PER_SEC);
}
実行結果 :
Enterキーを押下してください。
1.837000秒でした。
現在時刻の取得
time() 関数は、現在の時刻を返却する。
戻り値は time_t 型で、「1970年1月1日 0時0分0秒からの秒数」(UNIX時間)を表す。
ただこの time_t 型は秒単位の整数であり、そのままでは時刻として扱いにくい。
localtime() 関数を用ると tm 構造体に変換でき、時、分、秒など個別要素を取り出すことができるようになる。
#include <stdio.h>
#include <time.h>
void main(void)
{
time_t t1, t2;
// 下記のいずれの方法も有効
// time() 関数にポインタを渡すことで時刻を取得
time(&t1);
// time() 関数の戻り値として時刻を取得
t2 = time(NULL);
// t2 を tm 型に変換
struct tm* local = localtime(&t2);
// local の要素を出力
printf("%04d/", local->tm_year + 1900); //< 年
printf("%02d/", local->tm_mon + 1); //< 月
printf("%02d", local->tm_mday); //< 日
printf(" ");
printf("%02d:", local->tm_hour); //< 時
printf("%02d:", local->tm_min); //< 分
printf("%02d\n", local->tm_sec); //< 秒
char* const wdays[] = { "日", "月", "火", "水", "木", "金", "土" }; //< 曜日
printf("今日は%s曜日\n", wdays[local->tm_wday]);
}
実行結果 :
2012/01/23 01:23:45
今日は月曜日
tm 構造体の定義
tm_year | 1900年からの年 |
tm_mon | 1月からの月(0~11) |
tm_mday | 日 |
tm_hour | 時 |
tm_min | 分 |
tm_sec | 秒 |
tm_wday | 日曜日からの日数(0~6) |
tm_yday | 1月1日からの日数(0~365) |
tm_isdst | 夏時間フラグ
- 正 : 採用している
- 0 : 採用していない
- 負 : 不明
|
tm_mon 、tm_wday 、tm_yday はいずれも 0 起算であることに注意。