我正在尝试用clock_getres和clock_gettime来测量我的程序的一部分,用CLOCK_MONOTONIC时钟。
如果我理解正确的话,clock_gettime通过测量某种外部时钟(而不是cpu)来获取所经过的时间,并在他引用的struct timespec实例中更新它,作为paramer(即,它以纳秒精度返回结果)。
我需要知道的不是实际时间,而是时钟(CLOCK_MONOTONIC)产生的周期数。
我该怎么做呢?这可能与clock_getres有关,但我不能确切地理解它是如何工作的。
有没有人知道如何计算周期数?
发布于 2012-01-27 00:32:05
Clock_gettime为您提供了纪元(或过去的某个固定时间,取决于您的平台上的特定实现)与所选时钟(在您的例子中为CLOCK_MONOTONIC)上的当前时间之间经过的时间。
要测量一个进程需要多长时间,您需要调用它两次并计算差值。类似于:
int main()
{
timespec start, finish;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
//code you want to profile
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &finish);
//calculate the difference between start and finish
return 0;
}注意,这将为您提供一个时间值,如果您想知道CPU周期,则必须使用类似rdtsc的内容:
#include <stdio.h>
#include <intrin.h>
#pragma intrinsic(__rdtsc)
int main()
{
unsigned __int64 i;
i = __rdtsc();
printf_s("%I64d ticks\n", i);
}https://stackoverflow.com/questions/9021288
复制相似问题