gpt4 book ai didi

c++ - 10 毫秒 C++ 执行时间

转载 作者:太空宇宙 更新时间:2023-11-04 15:39:39 25 4
gpt4 key购买 nike

我尝试通过 2e6 次迭代找出“for 循环”的确切执行时间。以下代码是从 g++ for c++ 文件编译后在 10ms 内运行的。人们告诉我这是 C++ 编译器自动完成的优化代码,所以你得到无意义的执行时间。换句话说,因为没有任何输出调用例如变量 a、b、c 的 printf 或 cout<<,因此优化后的代码将不执行任何操作那个“for 循环”就是为什么我在 10 毫秒内得到非常短的程序执行时间。正确的 ?为什么他们说时间结果对于“for 循环”没有意义。

请指教

int main(){
int max = 2e6;
int a,b,c;
// CODE YOU WANT TO TIME
int start = getMilliCount();
for (int i = 0; i < max; i++) {
a = 1234 + 5678 + i;
b = 1234 * 5678 + i;
c=1234/2+i;
}
int milliSecondsElapsed = getMilliSpan(start);
printf("\n\nElapsed time = %u milliseconds %d\n", milliSecondsElapsed,max);
return 0;
}

最佳答案

运行时绝对不是没有意义。它至少证明了一个重点:优化器比给定的信用更聪明,并且它能够推断出循环没有副作用,因此将其删除。

所以即使profile结果只是证明了这一件事,它也确实有意义。

解决你想要的问题:

I try to find out the exact execution time for "for loop" with 2e8 iteritions.

2e8for 循环的执行时间可以是 0 如果没有可观察到的效果。或者如果它们很大的话。这就是您通常使用专用工具分析实际代码的原因。

关于c++ - 10 毫秒 C++ 执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25604514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com