我正在尝试测量 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);
}
最佳答案
三种选择
时钟()
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
关于c - 在 linux 中测量 c 程序的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14682824/