i++和++i的直观比较「控制变量法?」

实验方法

//输出运行时间
#include <bits/stdc++.h>
using namespace std;
const int MODE = 10000;

int main(){
    freopen("a1.txt", "w", stdout);
    int k = 100;
    while(k--){
        clock_t startTime,endTime;
        startTime = clock();
        for(int i = 1; i <= 1000000000;++i){
            //for(int i = 1; i <= 1000000000;i++)
        }
        endTime = clock();
        cout  << (double)(endTime - startTime) / CLOCKS_PER_SEC  << endl;
    }
    return 0;
}
//计算平均数
#include <bits/stdc++.h>
using namespace std;

int main(){
	double x, ans = 0;
	for(int i = 1; i <= 100; i++){
		cin >> x;
		ans += x;
	}
	cout << ans / 100 * 1.0 << endl;
	return 0;
}

实验数据

i++

实验结果(运行时间):有100组

1.49475 1.48689 1.48267 1.48717 1.46618 1.48366 1.48125 1.47547 1.4696 1.47904 
1.46063 1.46422 1.45806 1.47512 1.47688 1.46986 1.4765 1.48187 1.48523 1.48887 
1.48954 1.47565 1.47646 1.4869 1.47294 1.46999 1.49471 1.49482 1.47634 1.48114 
1.47966 1.48217 1.47516 1.48383 1.47035 1.47568 1.48959 1.48432 1.48831 1.48819 
1.48669 1.47704 1.48498 1.47897 1.48113 1.48686 1.48173 1.48589 1.48861 1.48378 
1.49177 1.48219 1.4862 1.48095 1.47826 1.48258 1.4792 1.48224 1.48175 1.47555 
1.47921 1.49453 1.48646 1.48491 1.47863 1.48674 1.48434 1.48744 1.48472 1.49569 
1.5065 1.48896 1.48461 1.48816 1.48729 1.48675 1.48197 1.45765 1.47828 1.48823 
1.48744 1.48439 1.48623 1.47405 1.48666 1.47727 1.47314 1.48107 1.48427 1.47678 
1.46141 1.48144 1.4827 1.49137 1.46822 1.45855 1.46609 1.47654 1.47576 1.46839 

平均:1.48089

++i

实验结果(运行时间):有100组

1.48783 1.47462 1.45892 1.45514 1.47138 1.4511 1.46779 1.47378 1.45837 1.46551 
1.47875 1.46085 1.45142 1.47746 1.45656 1.47044 1.45664 1.47624 1.45877 1.47537 
1.47389 1.4647 1.46883 1.45352 1.4651 1.47955 1.4608 1.47735 1.47621 1.46625 
1.48775 1.46162 1.45065 1.45032 1.48129 1.46423 1.48048 1.48697 1.47713 1.46541 
1.46152 1.48312 1.47812 1.45981 1.46816 1.47352 1.47586 1.48213 1.48329 1.48208 
1.49509 1.49124 1.48781 1.47985 1.4518 1.45328 1.47996 1.47313 1.48424 1.48727 
1.47213 1.4939 1.48238 1.4777 1.4944 1.4828 1.48939 1.48549 1.4705 1.48219 
1.48036 1.48001 1.47611 1.4691 1.48353 1.48807 1.48559 1.48342 1.4934 1.4859 
1.48992 1.49081 1.47789 1.4795 1.47973 1.48651 1.48731 1.48214 1.48623 1.47988 
1.48571 1.48232 1.48253 1.49288 1.4972 1.47673 1.47687 1.47443 1.47706 1.48272 

平均:1.47575

实验结论

++i的效率比i++更高

深度分析

++i 的操作等价于“i = i + 1”,在程序运行期间,直接将i本身赋值给变量
i++ 的操作等价于“int tmp = i, i = i + 1”,在程序运行期间,是将tmp的值赋值给变量,然后i再加1,由于需要使用临时变量tmp来存储当前的i值,所以效率较低

没有未来的未来不是我想要的未来
原文地址:https://www.cnblogs.com/Little-Turtle--QJY/p/13768720.html