简体   繁体   English

如何在C ++中计算函数的时间执行和CPU加速

[英]How to calculate time execution and cpu speding for a function in C++

I have finished writing a function and I want to compare time and cpu execution of the function with other function. 我已经完成了一个函数的编写,并且想将函数的时间和cpu执行与其他函数进行比较。 This is code to calculate time execution but I not sure it accuracy. 这是用于计算时间执行的代码,但我不确定它的准确性。 Do you have accuracy code to calculate time and cpu spending for one function in C++? 您是否有准确的代码来计算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." << "\n\n";
    return 0;
}

In C++11 you should use std::chrono::high_resolution_clock which under the hood uses the clock source with the smallest tick period provided by the system: 在C ++ 11中,应使用std::chrono::high_resolution_clock ,它在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);

For this particular code, I'm pretty sure your code is quite OK. 对于此特定代码,我很确定您的代码还可以。

For short periods, you may need to use more precise timing functions, such as Windows' QueryPerformanceCounter and QueryPerformanceFrequency to get higher precision timing. 在短期内,您可能需要使用更精确的计时功能,例如Windows的QueryPerformanceCounterQueryPerformanceFrequency才能获得更高的计时精度。

The easiest way I know of to get precise time estimates is to use an OpenMP function: 我知道获得精确时间估计的最简单方法是使用OpenMP函数:

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

In gcc compile with -fopenmp. 在gcc中,使用-fopenmp进行编译。 In visual studio turn on OpenMP support under C++/Language Support. 在Visual Studio中,在C ++ /语言支持下打开OpenMP支持。 BTW, OpenMP now works in Visual Studio 2012 express. 顺便说一句,OpenMP现在可以在Visual Studio 2012 Express中使用。 For CPU time profiling you can try http://developer.amd.com/tools-and-sdks/heterogeneous-computing/amd-codeanalyst-performance-analyzer/ 对于CPU时间分析,您可以尝试http://developer.amd.com/tools-and-sdks/heterogeneous-computing/amd-codeanalyst-performance-analyzer/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM