如何在c++中计算函数的执行时间和cpu消耗
visual How to calculate time execution and cpu speding for a function in C++
我已经写完了一个函数,我想比较一下这个函数和其他函数的时间和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的QueryPerformanceCounter
和QueryPerformanceFrequency
,以获得更高的精度定时。
我知道获得精确时间估计的最简单方法是使用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/
相关文章:
- 简单C++"Hello World"程序的执行时间长
- 我使用 OpenMP 的线程越多,执行时间就越长,这是怎么回事?
- 为什么切换 for 循环的顺序会显著改变执行时间?
- cmd.exe与Powershell中C++程序的不同执行时间
- pthread执行时间比顺序执行时间差
- OpenCV 函数 cv::remap() 的执行时间更长,当程序在两者之间进入睡眠状态时
- 为什么 std::chrono 在测量循环和编译器优化的并行 OpenMP 的执行时间时不起作用?
- 我需要帮助来缩短检索 SSL 证书的执行时间
- 如何测量cudaMalloc执行时间
- c++中的执行时间和检查流状态
- 为什么for循环中的异步不能提高执行时间
- 为什么 C++ openMP 程序执行时间更长
- 测量任何 Windows 可执行文件的内存使用情况和执行时间
- 需要减少我的C++代码的执行时间
- 如何在 ubuntu 上的 php 脚本中获取程序(c,c++,java,python,php)的执行时间和内存使用量?
- 在Qt中设置pixmap时的执行时间很奇怪
- 异步控制线程执行时间
- 如何对 g++ 设置执行时间限制?
- 如何在c++中计算函数的执行时间和cpu消耗
- 即使cpu数量增加,执行时间也会增加,为什么?