如何在linux中使用c时间来打印函数运行时间?

Eri*_*hen 2 c linux time

当我在linux中运行c代码时,代码总是不会打印出经过的时间,结果总是为0.代码如下:

#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);
}
Run Code Online (Sandbox Code Playgroud)

sar*_*old 6

不要忽视编译器警告; 你想打印方式中三个long变量(mtime,s,和us),就好像它们是doubleS:

fib.c: In function ‘main’:
fib.c:17:3: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘long int’
fib.c:17:3: warning: format ‘%f’ expects type ‘double’, but argument 3 has type ‘long int’
fib.c:19:3: warning: format ‘%f’ expects type ‘double’, but argument 4 has type ‘long int’
Run Code Online (Sandbox Code Playgroud)

更改suslong,并更改格式s,并us%ld和程序编译(并运行)无故障.


Bas*_*tch 6

所有建议实际上都有效,但时间测量的粒度很大(通常为10到100毫秒).所以它实际上测量了一些计算的东西,例如持续半秒.在当前的处理器上(运行速度为2到3Ghz,每个周期大约有3-5条指令),这意味着执行了十亿台机器指令(我们的C程序中的"基本步骤" - 通常有一个不明确的步骤概念)十几台机器说明).所以你的测试太小了,你真的应该计算一百万次fibion​​acci(10).

更具体地说,下面的程序(输出一些计算,以避免优化它们)在大约2秒内运行.(关于小于16的纤维蛋白计算的百万次计算).

#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);
  return 0;
}   
Run Code Online (Sandbox Code Playgroud)

time ./fib(编译gcc -O2 -Wall fib.c -o fib)输出的最后几行是

i=936079, f=610
i=948902, f=8
i=961725, f=233
i=974548, f=3
i=987371, f=89
2.140 cpu sec
./fib  2.15s user 0.00s system 99% cpu 2.152 total
Run Code Online (Sandbox Code Playgroud)

对小于大约一秒的运行进行基准测试并不是很有意义

(并且您可以使用该time命令来测量此类运行)

另请参见time(7)clock_gettime(2).