Simple for() loop benchmark takes the same time with any loop bound

后端 未结 5 1572
有刺的猬
有刺的猬 2020-12-11 19:50

I\'m willing to write a code that makes my CPU execute some operations and see how much time does he take to solve them. I wanted to make a loop going from i=0 to i<5000

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-11 20:21

    Because of the body of the for loop:

    i*434243;
    

    which does nothing, so assuming you are compiling the code with optimization flags enabled, the compiler wipes that out.

    Changing it to:

    int a = i*434243;
    

    would be likely be optimized out on anything else than -O0, so I wouldn't suggest it.

    Moreover, this will lead to Undefined Behavior, because overflowing, since the constant value you are using is relatively big, as i continues to increment.

    I suggest you do instead:

    int a = i * i;
    cout << a << "\n";   
    

提交回复
热议问题