关于循环速度的问题

dat*_*ili 5 c++ micro-optimization

我有以下两个循环:

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;
int main(){

    int start=clock();
    for (int i=0;i<100;i++)
        cout<<i<<" "<<endl;
    cout<<clock()-start<<"\n"<<endl;
    cout<<"\n";

    int start1=clock();
    for (int j=0;j<100;++j)
        cout<<j<<" "<<endl;
    cout<<"\n";
    cout<<clock()-start1<<" \n "<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我跑了三次.在前两次运行中,第二次循环最快,但在第三次运行时,第一次循环最快.这是什么意思?哪个更好?这取决于具体情况吗?

AnT*_*AnT 10

循环的运行时间绝大部分由输入输出操作决定.这意味着你观察到的时间1)与循环的实际性能无关(即i++vs ++j),2)几乎是不可预测和不稳定的(基本上是随机的).

换句话说,你的实验毫无意义.绝对没有任何意义.

最后,在++不使用内置运算符的结果的情况下,后缀和前缀增量之间绝对没有区别.在任何合理的编译器中,两个循环都将具有完全相同的性能.

  • 我敢打赌,如果他将这个编译成汇编语言,那么两个循环将完全相同 (2认同)

Rob*_*vić 5

在您的情况下,它可能是标准测量误差,您使用后增量或预增量无关紧要.对于标准类型(int,byte ...),这没关系.

但是您应该习惯使用预增量,因为如果您在类上使用它们会对性能产生影响,具体取决于这些运算符的实现方式.后增量运算符i ++必须复制该对象

例如:

class integer
{
public:
  integer(int t_value)
    : m_value(t_value)
  {
  }

  int get_value() { return m_value; }

  integer &operator++() // pre increment operator
  {
    ++m_value;
    return *this;
  }

  integer operator++(int) // post increment operator
  {
    integer old = *this; // a copy is made, it's cheap, but it's still a copy
    ++m_value;
    return old; // Return old copy
  }

private:
  int m_value;
Run Code Online (Sandbox Code Playgroud)

看看下面的答案

StackOverflow:i ++比++ i效率低,如何显示?