使用clock_gettime()每次执行获得的运行时间不一样

陆耀
2023-12-01
struct timespec start, end; //nanoseconds
double time_gen;
time_gen = 0.0;


clock_gettime(CLOCK_MONOTONIC, &start);

XX_gen(key);

clock_gettime(CLOCK_MONOTONIC, &end);

time_gen += (double) (1000 * (end.tv_sec - start.tv_sec)) + (double) (end.tv_nsec - start.tv_nsec)/1000000;

printf("\nTime for XX_gen is %8.6f mSec. \n",  time_gen);

问题描述:

But every time I run the program I am getting different results. What am I doing wrong?

解决方案:

When you say "different results", can you please be more specific? What ranges do you get? And since you use the wall clock, you are aware of that Linux is a multi-tasking operating kernel, that might pause your process and let other processes work, and you have no real control over how long or how many times your process might be paused, and that of course will skew your results. To get a better result, do the operation thousands (or even millions) of times, and calculate the average time. 

– Some programmer dude

 Sep 8 '15 at 

I've used this method of measuring before and you are doing nothing wrong. Even when you have your scheduling right your output will always fluctuate.

The overhead I used to have was around 250 microseconds if the thread didn't get interrupted by another process, but I suppose this is very dependent on the CPU power as well.

For the overhead: Try measuring a few hundreds/thousands times with an empty body, check the lowest (least interrupted) output to examine the overhead.

For your results: Try the same and take again the lowest value, this way you can approach the actual value you are looking for. Keep in mind that a single read and write might be not-measurable fast.

—— answered Sep 8 '15 at 14:12

koldewb

#define  TESTNUM 1000000

struct timespec start, end; //nanoseconds
double time_gen;
time_gen = 0.0;

clock_gettime(CLOCK_MONOTONIC, &start);
for (int i = 0; i < TESTNUM; i++)
{
    XX_gen(key);
}
clock_gettime(CLOCK_MONOTONIC, &end);

time_gen += (double) (1000 * (end.tv_sec - start.tv_sec)) + (double) (end.tv_nsec - start.tv_nsec)/1000000;

printf("\nTime for XX_gen is %8.6f mSec. \n",  time_gen/TESTNUM);

解决方案来源【版权侵删】:

c - Getting Inconsistent results with clock_gettime() - Stack Overflow

 类似资料: