我的代碼計算時鐘週期來創建線程計算時鐘週期給出了截然不同的結果
# 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。我環顧四周,但沒有真正找到解釋。這種行爲的原因是什麼?
究竟爲什麼你感到驚訝,如果算上完整的線程執行,而不是隻在啓動時你會得到一個更大的數字? – Voo