如何计算C++中函数的时间执行和cpu speding

use*_*476 1 c++ visual-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." << "\n\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

sya*_*yam 6

在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);
Run Code Online (Sandbox Code Playgroud)