【发布时间】:2014-06-12 10:42:46
【问题描述】:
我用于计算创建线程的时钟周期的代码是
# include <Windows.h>
# include <stdio.h>
# include <conio.h>
# define RUN 20000
DWORD WINAPI Calc(LPVOID Param){}
int main(int argc, char* agrv[])
{
ULONG64 Sum = 0;
for (int i = 0; i < RUN; i++)
{
ULONG64 ret = 0;
DWORD ThreadId;
HANDLE ThreadHandle;
/* create the thread */
ThreadHandle = CreateThread(
NULL, /* default security attributes */
0, /* default stack size */
Calc, /* thread function */
NULL, /* parameter to thread function */
0, /* default creation flags */
&ThreadId); /* returns the thread identifier */
QueryThreadCycleTime(ThreadHandle, &ret);
WaitForSingleObject(ThreadHandle, INFINITE);
CloseHandle(ThreadHandle);
Sum += ret;
}
printf_s("The Average no of cycles in %d runs is %lu\n", RUN, (DWORD)(Sum/RUN));
_getch();
return 0;
}
这段代码的结果是在我普通的笔记本电脑上大约 1000 个时钟周期。但是,如果我在 WaitForSingleObject 函数之后调用 QueryThreadCycleTime 函数,结果会非常不同,大约为 200,000。我环顾四周,但并没有真正找到解释。这种行为的原因是什么?
【问题讨论】:
-
如果你计算完整的线程执行而不是只计算启动时间,你会得到一个更大的数字,为什么你会感到惊讶?
标签: c multithreading winapi