C - 使用<time.h>以毫秒为单位的程序执行时间

时间:2016-09-18 15:34:10

标签: c execution

我正在尝试使用时间标头获取程序的执行时间,但找不到任何仅使用<time.h>而非<sys/time.h>的资源。

我试过

 time_t startTime;                
 time_t endTime;                 
 long double execTime;           

 /* Start timer */
 time(&startTime);

 ..STUFF THAT TAKES TIME..

time(&endTime); 
execTime = difftime(endTime, startTime); 

printf("Computing took %Lf\n", execTime * 1000);

但是每次打印出来都是0 ..我猜是因为时间是一个整数而且我的过程不到一秒钟。

如何以毫秒显示执行?

谢谢

3 个答案:

答案 0 :(得分:3)

虽然clock_gettime应该是首选方式,但它是Posix,而不是标准C.它们只有clock。它有许多缺点,但足以进行快速和脏的测量。

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main()
{
  int i, j, a[1000000] = { 0 };
  clock_t start, stop;
  srand(0xdeadbeef);
  start = clock();
  // play around with these values, especially with j
  for (j = 0; j < 100; j++) {
    for (i = 0; i < 1000000; i++) {
      a[i] = rand() % 123;
      a[i] += 123;
    }
  }
  stop = clock();
  printf("Time %.10f seconds\n", (double) (stop - start) / CLOCKS_PER_SEC);
  exit(EXIT_SUCCESS);
}

答案 1 :(得分:2)

衡量时间的正确方法是使用clock_gettime(CLOCK_MONOTONIC, &ts_current);

另外,gettimeofday() should be avoided

使用clock_gettime()测量时差的完整示例(秒和纳秒,可以转换为毫秒):

#include <stdio.h>
#include <time.h>

struct timespec diff(struct timespec start, struct timespec end)
{
    struct timespec temp;
    if ((end.tv_nsec-start.tv_nsec)<0) {
        temp.tv_sec = end.tv_sec-start.tv_sec-1;
        temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
    } else {
        temp.tv_sec = end.tv_sec-start.tv_sec;
        temp.tv_nsec = end.tv_nsec-start.tv_nsec;
    }
    return temp;
}

int main()
{
    struct timespec time1, time2;
    int temp = 0;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
    for (int i = 0; i< 242000000; i++)
        temp+=temp;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
    printf("Time difference: %ld [s] %ld [ns]", (long) diff(time1,time2).tv_sec, (long) diff(time1,time2).tv_nsec);
    return 0;
}

答案 2 :(得分:1)

time功能只有1秒的分辨率。相反,请使用具有微秒分辨率的gettimeofday

struct timeval tstart, tend;
gettimeofday(&tstart, NULL);
// do something that takes time
gettimeofday(&tend,NULL);