如何在c++中计算函数的执行时间和cpu消耗

visual How to calculate time execution and cpu speding for a function in C++

本文关键字:执行时间 cpu 消耗 函数 计算 c++      更新时间:2023-10-16

我已经写完了一个函数,我想比较一下这个函数和其他函数的时间和cpu执行情况。这是计算时间执行的代码,但我不确定它的准确性。你有精确的代码来计算一个函数在c++中的时间和cpu开销吗?

//Only time execution. CPU spending?
 #include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    clock_t start, end;
    start = clock();
    for(int i=0;i<65536;i++)
    cout<<i<<endl;
    end = clock();
    cout << "Time required for execution: "
    << (double)(end-start)/CLOCKS_PER_SEC
    << " seconds." << "nn";
    return 0;
}

在c++ 11中,您应该使用std::chrono::high_resolution_clock,它在底层使用系统提供的具有最小滴答周期的时钟源:

#include <chrono>
auto start = std::chrono::high_resolution_clock::now();
//...
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);

对于这个特定的代码,我非常确定您的代码是相当好的。

对于短时间,您可能需要使用更精确的定时功能,例如Windows的QueryPerformanceCounterQueryPerformanceFrequency,以获得更高的精度定时。

我知道获得精确时间估计的最简单方法是使用OpenMP函数:

#include <stdio.h>
#include <omp.h>
int main() {
    double dtime = omp_get_wtime();
    foo();
    dtime = omp_get_wtime() - dtime;
    printf("time in seconds %fn", dtime);
}

在gcc中使用-fopenmp编译。在visual studio中,在c++/语言支持下打开OpenMP支持。顺便说一句,OpenMP现在可以在Visual Studio 2012 express中工作。对于CPU时间分析,您可以尝试http://developer.amd.com/tools-and-sdks/heterogeneous-computing/amd-codeanalyst-performance-analyzer/