clock
NAME
clock - Determine processor time
SYNOPSIS
#include <time.h>
clock_t clock(void);
DESCRIPTION
The clock() function returns an approximation of processor time used by the program.
RETURN VALUE
The value returned is the CPU time used so far as a clock_t; to get the number of seconds used,
divide by CLOCKS_PER_SEC. If the processor time used is not available or its value cannot be
represented, the function returns the value (clock_t) -1.
times
NAME
times - get process and waited-for child process times
SYNOPSIS
#include <sys/times.h>
clock_t times(struct tms *buffer);
RETURN VALUE
Upon successful completion, times() shall return the elapsed real time, in clock ticks, since an
arbitrary point in the past (for example, system start-up time). This point does not change from
one invocation of times() within the process to another. The return value may overflow the possi‐
ble range of type clock_t. If times() fails, (clock_t)-1 shall be returned and errno set to indi‐
cate the error.
void exp_times()
{
clock_t ct1,ct2;
int i;
double j=1.2;
struct tms tms_start,tms_end;
printf("sysconf( _SC_CLK_TCK ):%ld\n",sysconf( _SC_CLK_TCK ));
printf("CLOCKS_PER_SEC: %ld\n", CLOCKS_PER_SEC);
ct1 = times(&tms_start);
sleep(2);
ct2 = times(&tms_end);
printf("takes :%ld\tuser :%ld\tsys :%ld\n",ct2 - ct1,tms_end.tms_utime - tms_start.tms_utime,
tms_end.tms_utime - tms_start.tms_utime);
ct1 = times(&tms_start);
for(i=0 ;i<100000;i++)
time(NULL);
ct2 = times(&tms_end);
printf("takes :%ld\tuser :%ld\tsys :%ld\n",ct2 - ct1,tms_end.tms_utime - tms_start.tms_utime,
tms_end.tms_utime - tms_start.tms_utime);
}
结果:
sysconf( _SC_CLK_TCK ):100
CLOCKS_PER_SEC: 1000000
takes :200 user :0 sys :0 /*sleep 自然导致系统和用户时间为0*/
takes :14 user :4 sys :4 /**/
void exp_clock()
{
clock_t ct1,ct2,ct3,ct4;
int i;
double j=1.2;
struct tms tms_start,tms_end;
ct1 = clock();
sleep(2);
ct2 = clock();
printf("clock1 =%lf\n",(double)(ct2-ct1)/CLOCKS_PER_SEC);
ct3 = clock();
for(i=0 ;i<100000;i++)
time(NULL);
ct4 = clock();
printf("clock2 =%lf\n",(double)(ct4-ct3)/CLOCKS_PER_SEC);
}
结果:
clock1 =0 /*clock只是计算cpu时间,所以sleep不会计算在内,也就是0*/
clock2 =0.140000 /*对照times函数中对该循环时间的统计(takes :14 user :4 sys :4 ),此值还是合理的*/
void exp_gettimeoffday()
{
struct timeval stv1 = {0};
struct timeval stv2 = {0};
int i;
gettimeofday(&stv1,NULL);
printf("sec:%ld,usec:%ld\n",stv1.tv_sec,stv1.tv_usec);
sleep(1);
gettimeofday(&stv1,NULL);
printf("sec:%ld,usec:%ld\n",stv1.tv_sec,stv1.tv_usec);
gettimeofday(&stv1,NULL);
printf("sec:%ld,usec:%ld\n",stv1.tv_sec,stv1.tv_usec);
for(i=0 ;i<100000;i++)
time(NULL);
gettimeofday(&stv2,NULL);
printf("sec:%ld,usec:%ld\n",stv2.tv_sec,stv2.tv_usec);
printf("cost :%lf\n",(stv2.tv_sec - stv1.tv_sec) + (double)(stv2.tv_usec - stv1.tv_usec)/1000000);
}
结果:// 该函数为计算系统时间流逝。不能准确作为进程时间消耗的cpu资源。
sec:1341393579,usec:433367