我正在一个函数中执行一些操作my_task
。我想计算 CPU 执行这个函数需要多少时间(或时钟周期),因为我要对这个函数进行性能改进。所以我参考了windows API并编写了下面的代码。
typedef struct timer
{
LARGE_INTEGER t1;
LARGE_INTEGER t2;
LARGE_INTEGER frequency;
}MY_TIMER_S;
int start_timer(MY_TIMER_S *a)
{
QueryPerformanceFrequency(&a->frequency);
QueryPerformanceCounter(&a->t1);
}
int stop_timer(MY_TIMER_S *a)
{
double elsapsedtime;
QueryPerformanceCounter(&a->t2);
elapsedtime = (a->t2.QuadPart - a->t1.QuadPart) * 1000.0 / a->frequency.QuadPart;
printf("Elapsed time is %lf ms\n", elapsedtime);
}
void main()
{
MY_TIMER_S a = {0};
int i = 0;
for (i = 0; i < 3; i++)
{
start_timer(&a);
my_task();
stop_timer(&a);
}
}
输出是
Elapsed time is 0.113352 ms
Elapsed time is 0.203253 ms
Elapsed time is 0.104254 ms
这三个值精确到纳秒,但不精确。我之所以这样想,是因为在我的系统中并行运行的其他应用程序发生了进程切换。我检查了我的任务管理器,它显示为 124 个进程正在运行。所以我重新启动了我的系统(现在任务管理器中有 84 个进程),然后输出是
Elapsed time is 0.083162 ms
Elapsed time is 0.113223 ms
Elapsed time is 0.074258 ms
在我用start /high
command执行我的 exe 之后,我也没有得到精度值。
我的问题是如何在 windows 或 linux 中以更精确的方式计算函数的运行时间。
环境:i5 处理器上的 32 位 Windows 7,带有 Visual Studio 2005 C 编译器的 4Gb 内存