C语言 以毫秒精度测量时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16764276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Measuring time in millisecond precision
提问by MegaWidget
My program is going to race different sorting algorithms against each other, both in time and space. I've got space covered, but measuring time is giving me some trouble. Here is the code that runs the sorts:
我的程序将在时间和空间上相互竞争不同的排序算法。我有足够的空间,但测量时间给我带来了一些麻烦。这是运行排序的代码:
void test(short* n, short len) {
short i, j, a[1024];
for(i=0; i<2; i++) { // Loop over each sort algo
memused = 0; // Initialize memory marker
for(j=0; j<len; j++) // Copy scrambled list into fresh array
a[j] = n[j]; // (Sorting algos are in-place)
// ***Point A***
switch(i) { // Pick sorting algo
case 0:
selectionSort(a, len);
case 1:
quicksort(a, len);
}
// ***Point B***
spc[i][len] = memused; // Record how much mem was used
}
}
(I removed some of the sorting algos for simplicity)
(为简单起见,我删除了一些排序算法)
Now, I need to measure how much time the sorting algo takes. The most obvious way to do this is to record the time at point (a) and then subtract that from the time at point (b). But none of the C time functions are good enough:
现在,我需要测量排序算法花费的时间。最明显的方法是记录 (a) 点的时间,然后从 (b) 点的时间中减去该时间。但是没有一个 C 时间函数足够好:
time()gives me time in seconds, but the algos are faster than that, so I need something more accurate.
time()以秒为单位给我时间,但算法比这更快,所以我需要更准确的东西。
clock()gives me CPU ticks since the program started, but seems to round to the nearest 10,000; still not small enough
自程序启动以来,clock()给了我 CPU 滴答,但似乎四舍五入到最接近的 10,000;还是不够小
The timeshell command works well enough, except that I need to run over 1,000 tests per algorithm, and I need the individual time for each one.
该时间shell命令的作品不够好,但我需要运行每个算法超过1000测试,我需要为每一个单独的时间。
I have no idea what getrusage()returns, but it's also too long.
我不知道getrusage()返回什么,但它也太长了。
What I need is time in units (significantly, if possible) smaller than the run time of the sorting functions: about 2ms. So my question is: Where can I get that?
我需要的是单位时间(如果可能的话)小于排序函数的运行时间:大约 2ms。所以我的问题是:我在哪里可以得到它?
回答by
gettimeofday()has microseconds resolution and is easy to use.
gettimeofday()具有微秒级分辨率且易于使用。
A pair of useful timer functions is:
一对有用的定时器函数是:
static struct timeval tm1;
static inline void start()
{
gettimeofday(&tm1, NULL);
}
static inline void stop()
{
struct timeval tm2;
gettimeofday(&tm2, NULL);
unsigned long long t = 1000 * (tm2.tv_sec - tm1.tv_sec) + (tm2.tv_usec - tm1.tv_usec) / 1000;
printf("%llu ms\n", t);
}
回答by TheBuzzSaw
For measuring time, use clock_gettimewith CLOCK_MONOTONIC(or CLOCK_MONOTONIC_RAWif it is available). Where possible, avoid using gettimeofday. It is specifically deprecated in favor of clock_gettime, and the time returned from it is subject to adjustments from time servers, which can throw off your measurements.
要测量时间,请使用clock_gettimewith CLOCK_MONOTONIC(或CLOCK_MONOTONIC_RAW如果可用)。在可能的情况下,避免使用gettimeofday. 它特别被弃用,支持clock_gettime,并且从它返回的时间会受到时间服务器的调整,这可能会影响您的测量。
回答by paddy
You can get the total user + kernel time (or choose just one) using getrusageas follows:
您可以使用以下方法获得总用户 + 内核时间(或仅选择一个)getrusage:
#include <sys/time.h>
#include <sys/resource.h>
double get_process_time() {
struct rusage usage;
if( 0 == getrusage(RUSAGE_SELF, &usage) ) {
return (double)(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) +
(double)(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) / 1.0e6;
}
return 0;
}
I elected to create a doublecontaining fractional seconds...
我选择创建一个double包含小数秒...
double t_begin, t_end;
t_begin = get_process_time();
// Do some operation...
t_end = get_process_time();
printf( "Elapsed time: %.6f seconds\n", t_end - t_begin );
回答by Imre Kerr
The Time Stamp Counter could be helpful here:
时间戳计数器在这里可能会有所帮助:
static unsigned long long rdtsctime() {
unsigned int eax, edx;
unsigned long long val;
__asm__ __volatile__("rdtsc":"=a"(eax), "=d"(edx));
val = edx;
val = val << 32;
val += eax;
return val;
}
Though there are some caveats to this. The timestamps for different processor cores may be different, and changing clock speeds (due to power saving features and the like) can cause erroneous results.
尽管对此有一些警告。不同处理器内核的时间戳可能不同,改变时钟速度(由于节能功能等)可能会导致错误的结果。

