Linux 计时

Linux 常见计时系统调用如下:

序号函数类型精度级别时间
1timeC系统调用<1s
2timesC系统调用<10ms
3clockC系统调用<10ms
4gettimeofday linux环境下C系统调用<0.1ms


Example:

#include <stdio.h>
#include <time.h>	/*time, clock*/
#include <sys/times.h>	/*times*/
#include <sys/time.h>	/*gettimeofday*/
#include <stdlib.h>
#include <unistd.h>

#define COUNT 10000
#define RESOLUTION 1000000.0

/*100*/
long tick_per_sec()
{
	return sysconf(_SC_CLK_TCK);
}

int foo()
{
	int index = 0;
	for(int i = 0; i < COUNT; i++)
	{
		for(int j = 0; j < COUNT; j++)
		{
			index++;
		}
	}
	
	return 0;
}

/*time, resolution: second*/
time_t time_test1()
{
	time_t start_time;
	time_t elapsed_time;
	
	start_time = time(NULL);	
	foo();
	
	elapsed_time = time(NULL) - start_time;
	printf("time => elapsed time: %f\n", (double)elapsed_time);	
	return elapsed_time;
}
/*times, resolution: mili second*/
clock_t time_test2()
{
	clock_t start_time;
	double elapsed_time;
	struct tms buf;
	
	start_time = times(&buf);
	foo();
	elapsed_time = times(&buf) - start_time;
	elapsed_time /= tick_per_sec();
	//printf("tick_per_sec = %ld\n", tick_per_sec());
	printf("times => elapsed time: %fs\n",elapsed_time);	
	return elapsed_time;
}

/*clock, resolution: mili second
  return the CPU time used, to get the number of seconds used, divide by CLOCKS_PER_SEC.*/
clock_t time_test3()
{
	clock_t start_time;
	clock_t elapsed_time;
	start_time = clock();
	foo();
	elapsed_time = clock() - start_time;
	printf("clock => elapsed time: %fs\n", (double)elapsed_time/CLOCKS_PER_SEC);
	return elapsed_time;
}

/*gettimeofday, resolution: micro second*/
double time_test4()
{
	double elapsed_time;
	struct timeval tv1, tv2;
	struct timezone tz1, tz2;
	
	gettimeofday(&tv1, &tz1);	
	foo();
	gettimeofday(&tv2, &tz2);
	
	elapsed_time = (tv2.tv_sec + tv2.tv_usec/RESOLUTION) - (tv1.tv_sec + tv1.tv_usec/RESOLUTION);

	printf("gettimeofday => elapsed time: %fs\n", elapsed_time);
	return elapsed_time;
}	
int main(int argc, char* argv[])
{
	/*
	if(argc != 2)
	{
		printf("USAGE: binfile number\n");
		exit(EXIT_FAILURE);
	}
	int index = atoi(argv[1]);
	*/
		time_test1();	//time
		time_test2();	//times
		time_test3();	//clock
		time_test4();	//gettimeofday
}


输出结果:

time => elapsed time: 1.000000
times => elapsed time: 0.310000s
clock => elapsed time: 0.310000s
gettimeofday => elapsed time: 0.317607s


2012. 8. 26

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值