我有以下C++代码(为了简单起见,我对其进行了简化。)
int main()
{
string runCommand="./runAnotherCppProgram.out";
for (int i=0; i<5; i++)
{
system(runCommand.c_str());
}
return 0;
}
现在我想知道 runAnotherCppProgram.out 在每次迭代中花费了多少时间。为此,我做了以下事情:
int main()
{
string runCommand = "./runAnotherCppProgram.out";
for (int i=0; i<5; i++)
{
clock_t clockStart = clock();
system(runCommand.c_str());
double finish = (double)(clock() - clockStart)/CLOCKS_PER_SEC;
cout << finish << endl;
}
return 0;
}
但是,它提供的实际执行时间要少得多。可能是什么问题?
最佳答案
如果您可以访问 C++11....
#include <chrono>
和
auto start = std::chrono::steady_clock::now();
//DO SOMETHING HERE
auto stop = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop-start).count();
std::cout << "Running time was: " << ((double)duration / 1000.0) << "s" << std::endl;
你可以玩弄你施放它的单位以及你想如何显示它......(也就是我做了毫秒然后除以 1000 得到带有一些小数点的秒,持续时间以整数形式出现所以它如果你只要求几秒钟,将会四舍五入)
关于c++ - 在 C++ 中查找程序的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30354954/