当我运行在Linux下C代码,这个代码总是犯规打印出经过时间,而结果总是0.The代码只是如下:如何在linux中使用c时间来打印函数运行时间?
#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);
}
Excellect的工作,thx很多Starynkevitch –