好的,现在我已经弄清楚了时间问题,完全修改了我的问题。所以现在这就是我的代码的样子;
int main()
{
int start_s = clock();
int i, n = 10;
int sum = 0;
for (i = 0; i < n; ++i)
{
cout << "Sum: " << sum << "\n";
++sum;
int stop_s = clock();
cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000 << endl;
system("pause");
}
}
但现在我的问题是执行时间以奇怪的数字显示,例如我第一次运行它时我说时间:1,然后再次运行它会上升到一些奇怪的东西,比如时间:4000,等等。我如果可能的话,需要以毫秒为单位的时间,或者类似 0.0043 的时间。
感谢您的帮助!
最佳答案
你必须将 (stop_s - start_s)
转换成双倍。请看下面的代码。
t = (stop_s - start_s);
double time_taken = (((double)t)/CLOCKS_PER_SEC) * 1000; //time in milliseconds
int main()
{
int start_s = clock();
int i, n = 10;
int sum = 0;
for (i = 0; i < n; ++i)
{
cout << "Sum: " << sum << "\n";
++sum;
int stop_s = clock();
double t = double (stop_s - start_s);
cout << "time: " << (t / double(CLOCKS_PER_SEC)) * 1000 << endl;
system("pause");
}
}
这应该可以,但是我现在无法测试它。
关于c++ - 如何在命令框输出中显示执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42918504/