Linux下关于时间概念的C语言编程(2)

的差就是做该事情所消耗的时间.
例程:计算函数function()的耗时
time.c
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void function() /* 算法分析 */
{
unsigned int i,j;
double y;
for(i=0;i<1000;i++)
for(j=0;j<1000;j++)
y++;
}
void main()
{
struct timeval tpstart,tpend;
float timeuse;
gettimeofday(&tpstart,null); // 开始时间
function();
gettimeofday(&tpend,null); // 结束时间
/* 计算执行时间,以微秒为单位进行计算 */
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000000;
printf("used time:%f\n",timeuse);
exit(0);
}
执行结果:
[root@localhost lishuai]# gcc time.c -o time -wall
[root@localhost lishuai]# ./time
use time:0.006288


6.延时函数
<1>使程序睡眠seconds秒
unsigned int sleep(unsigned int seconds)
函数功能:使程序睡眠seconds秒
参数:需要休眠的秒数
<2>使程序睡眠usec微秒
void usleep(unsigned long usec)
函数功能:使程序睡眠usec微秒
参数:需要休眠的秒数

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/386bec641eb4fbe0dec6a7fdffc94f7c.html