我正在尝试测量Linux中的运行时间.我的回答一直归零,这对我来说毫无意义.以下是我在程序中测量时间的方法.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
main()
{
double p16 = 1, pi = 0, precision = 1000;
int k;
unsigned long micros = 0;
float millis = 0.0;
clock_t start, end;
start = clock();
// This section calculates pi
for(k = 0; k <= precision; k++)
{
pi += 1.0 / p16 * (4.0 / (8 * k + 1) - 2.0 / (8 * k + 4) - 1.0 / (8 * k + 5) - 1.0 / (8 * k + 6));
p16 *= 16;
}
end = clock();
micros = end - start;
millis = micros / 1000;
printf("%f\n", millis); //my time keeps being returned as 0
printf("this value of pi is : %f\n", pi);
}
Run Code Online (Sandbox Code Playgroud)
Shr*_*han 14
三种选择
clock()
gettimeofday()
clock_gettime()
clock_gettime()
达到纳秒精度,它支持4个时钟.
CLOCK_REALTIME
系统范围的实时时钟.设置此时钟需要适当的权限.
CLOCK_MONOTONIC
无法设置的时钟,表示自某些未指定的起点以来的单调时间.
CLOCK_PROCESS_CPUTIME_ID
来自CPU的高分辨率每进程计时器.
CLOCK_THREAD_CPUTIME_ID
特定于线程的CPU时钟.
你可以用它作为
#include <time.h>
struct timespec start, stop;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
/// do something
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop);
double result = (stop.tv_sec - start.tv_sec) * 1e6 + (stop.tv_nsec - start.tv_nsec) / 1e3; // in microseconds
Run Code Online (Sandbox Code Playgroud)
注意:clock()函数返回进程的CPU时间,而不是挂钟时间.我相信这是OP感兴趣的.如果需要挂钟时间,那么gettimeofday()是一个很好的选择,如前面的答案所示.如果你的系统支持,clock_gettime()可以做任何一个; 在我的linux嵌入式系统上,不支持clock_gettime(),但是clock()和gettimeofday()是.
以下是使用gettimeofday()获取挂钟时间的代码
#include <stdio.h> // for printf()
#include <sys/time.h> // for clock_gettime()
#include <unistd.h> // for usleep()
int main() {
struct timeval start, end;
long secs_used,micros_used;
gettimeofday(&start, NULL);
usleep(1250000); // Do the stuff you want to time here
gettimeofday(&end, NULL);
printf("start: %d secs, %d usecs\n",start.tv_sec,start.tv_usec);
printf("end: %d secs, %d usecs\n",end.tv_sec,end.tv_usec);
secs_used=(end.tv_sec - start.tv_sec); //avoid overflow by subtracting first
micros_used= ((secs_used*1000000) + end.tv_usec) - (start.tv_usec);
printf("micros_used: %d\n",micros_used);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
首先,您需要使用浮点运算。任何整数值除以更大的整数值将始终为零。
当然,您实际上应该在获取开始时间和结束时间之间做一些事情。
顺便说一句,如果您有权访问gettimeofday
它,通常会更喜欢它,clock
因为它具有更高的分辨率。或者可能clock_gettime
具有更高的分辨率。