當我運行在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 –