2013-04-18 57 views
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; 
} 
+0

有很多因素,有些可能会影响您的结果。 (如缓存大小,硬盘驱动器碎片状态,分页等)。进一步在抢先式多任务操作系统上如果操作系统中断您的线程,该怎么办 –

+1

根据MSDN,QueryThreadCycleTime包含在内核模式下花费的CPU周期。当I/O中断发生时,I/O处理发生在当时正在运行的任何线程中。因此,您收集的统计信息可能包含与您的代码无关的活动。 –

回答