経過時間の調べ方

(動作保証なし.サポート対象外.)

経過時間を細かく調べたい場合, 関数 gettimeofday() を使えばよいだろう. 使用例として,ストップウォッチを作ってみた:

#include <ncurses.h>

#include <sys/time.h>

double Time()
{
	static struct timeval	tv;

	gettimeofday(&tv, NULL);
	// 構造体変数 tv に現在時刻の情報をμ 秒単位で取得.
	// メンバ変数 int tv_sec には秒の成分,
	// int tv.tv_usec にはμ秒の成分が入る.

	return ((double)tv.tv_sec + (double)tv.tv_usec*1.0e-06);
	// 2つの成分を1つの実数値にまとめて返す.
	// (1.0e-06 は 10の-6乗,つまり μ.)
}

int main(int argc, char **argv)
{
	double t0, t;

	initscr();
	timeout(-1);
	printw("Push [Enter] to start.\n");
	getch();	// [Enter]キーでスタート

	t0 = Time();
	printw("Started at %f\n", t0);

	printw("Push [Enter] to stop.\n");
	getch();	// [Enter]キーでストップ

	t = Time();
	printw("Stopped at %f\n", t);

	printw("Time: %f (sec)\n", t - t0);
	getch();

	endwin();

	return (0);
}


(c) 2014, yanagawa@kushiro-ct.ac.jp