背景知识:
1. time() 函数 - get time in seconds
Synopsis
#include <time.h>time_t time(time_t *t);
Description
time () returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).If t is non-NULL, the return value is also stored in the memory pointed to by t.
Return value:
On success, the value of time in seconds since the Epoch is returned. On error, ((time_t) -1) is returned, and errno is set appropriately.
2. 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.
网上有人用time() 函数,想得到Fibo(10)的运行时间:
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void main(int argc,char* argv[]){
int n;
if(argc == 2){
n = atoi(argv[1]);
}
struct timeval start, end;
gettimeofday(&start, 0);
int r = fib(n);
gettimeofday(&end, 0);
long mtime, s,us;
s = end.tv_sec - start.tv_sec;
us = end.tv_usec - start.tv_usec;
printf("s=%f,us=%f \n", s, us);
mtime = (s*1000 + us/1000.0)+0.5;
printf("Fib result for %d is: %d;elapsing %f \n", n, r, mtime);
}
int fib(int n){
if(n == 0) return 0;
if(n == 1) return 1;
return fib(n-1)+fib(n-2);
}
所以必须多次运行函数,然后得到函数运行时间的平均值:
下面是用clock() 来得到函数运行的平均时间:
#include <stdio.h>
#include <unistd.h>
#include <time.h>
long fib(int n){
if(n == 0) return 0;
if(n == 1) return 1;
return fib(n-1)+fib(n-2);
}
int main ()
{
int i=0;
int p = (int) getpid();
clock_t cstart = clock();
clock_t cend = 0;
for (i=0; i<1000000; i++) {
long f = fib(i%16);
if (i % p == 0) printf("i=%d, f=%ld\n", i, f);
}
cend = clock();
printf ("%.3f cpu sec\n", ((double)cend - (double)cstart)* 1.0e-6); //类似于:((double)cend - (double)cstart)/CLOCKS_PER_SEC
return 0;
}