0
我想測量在Windows上執行某些代碼所花費的CPU週期。在運行上面的代碼時(Visual C++ 11),我注意到CPU運行週期可能因運行而異。由於沒有明確的I/O,我不知道爲什麼會發生這種情況。CPU週期數作爲執行指令數的近似值
一般來說,線程花費的CPU週期與執行的指令數量之間的關係是什麼?我可以使用CPU週期作爲近似值嗎?
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <algorithm>
int _tmain(int argc, _TCHAR* argv[])
{
unsigned __int64 thread_cycle1;
unsigned __int64 thread_cycle2;
HANDLE thread_handle = GetCurrentThread();
QueryThreadCycleTime(thread_handle, &thread_cycle1);
// Code for profiling
int a[] = {1,3,4,5,6,7,23,4,2,6,7,8,9};
std::sort(a, a + sizeof(a)/sizeof(a[0]));
QueryThreadCycleTime(thread_handle, &thread_cycle2);
std::cout << thread_cycle2 - thread_cycle1 << " cycles";
return 0;
}
有很多因素,有些可能會影響您的結果。 (如緩存大小,硬盤驅動器碎片狀態,分頁等)。進一步在搶先式多任務操作系統上如果操作系統中斷您的線程,該怎麼辦 –
根據MSDN,QueryThreadCycleTime包含在內核模式下花費的CPU週期。當I/O中斷髮生時,I/O處理髮生在當時正在運行的任何線程中。因此,您收集的統計信息可能包含與您的代碼無關的活動。 –