[英]++i vs i++ ? Why is i++ faster while ++i is supposed to be faster?
++i is supposed to be faster than i++ right?? ++i 应该比 i++ 快对吧? Then why this o/p??
那为什么这个o/p?? Below is the code in CPP
以下是CPP中的代码
start = clock();
srand(time(NULL));
cout<<"++i"<<endl;
for(int i=0;i!=-1;++i);
end = clock();
total_time = ((double) (end - start)) / CLOCKS_PER_SEC;
cout<<"Time taken for ++i : "<<total_time<<"\n\n";
start = clock();
srand(time(NULL));
cout<<"i++"<<endl;
for(int i=0;i!=-1;i++);
end = clock();
total_time = ((double) (end - start)) / CLOCKS_PER_SEC;
cout<<"Time taken for i++ : "<<total_time<<endl;
And this is the output这是 output
++i Time taken for ++i: 12.2812
++i ++i 所用时间:12.2812
i++ Time taken for i++: 12.125
i++ i++ 所用时间:12.125
Indeed conceptually at least ++i
will never be slower than i++
due to the latter somehow storing the original value for later return.实际上,至少在概念上
++i
永远不会比i++
慢,因为后者以某种方式存储原始值以供以后返回。
But you are forgetting an important concept: the as-if rule.但是你忘记了一个重要的概念: as-if规则。 All modern compilers will optimise
++i
and i++
to the same thing.所有现代编译器都会将
++i
和i++
优化为相同的东西。
Note furthermore that a good compiler will optimise the undefined statement (due to int
overflow) for(int i=0;i;=-1;++i);
此外请注意,一个好的编译器会优化未定义的语句(由于
int
溢出) for(int i=0;i;=-1;++i);
to a no-op.到无操作。 Many would also do so if
i
was an unsigned
type.如果
i
是unsigned
类型,许多人也会这样做。 This is because its inclusion or otherwise has no effect on the program.这是因为它的包含或以其他方式对程序没有影响。
clock ()
method is not a good way to calculate the time difference clock ()
方法不是计算时差的好方法
maybe you can use也许你可以使用
high_resolution_clock::now()
If you want to understand why pre-increment should be faster, you must implement both and see the differences.如果您想了解为什么预增量应该更快,您必须同时实现两者并查看差异。 This is how pre-increment would look like for a class that wraps an integer (
i_
):这是包装 integer (
i_
) 的 class 的预增量的样子:
my_int_t& operator++()
{
++i_;
return *this;
}
And this how the post-increment would look like:这就是后增量的样子:
my_int_t operator++( int )
{
my_int_t r( *this );
++i_;
return r;
}
Notice the different number of lines.注意不同的行数。 More lines equals longer execution time IF the optimizations are turned off .
如果优化被关闭,更多的行等于更长的执行时间。 If the optimizations are turned on, this might no longer be true - what you see is not what the compiler generates (although equivalent, most of the times).
如果启用了优化,这可能不再是真的 - 你看到的不是编译器生成的(尽管大多数时候是等效的)。
See this demo for the expected result - notice #pragma GCC optimize ("O0")
.有关预期结果,请参阅此演示- 通知
#pragma GCC optimize ("O0")
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.