闲的没事,做了一个小测试
目前主流的在循环上卡常的方法有:
for(register int I=1...)
//I(1)貌似没多大作用
for(...;++I)
for(...;I=-~I)
这是测试代码
#include<iostream>
#include<ctime>
using namespace std;
unsigned int test1,test2,test3,test4,test5;
int main(){
int fst=clock();
for(int i=1;i<=100000001;i++){
test1+=i;
// test1<<=i;
}
int sc=clock();
for(register int i=1;i<=100000001;i++){
// test2+=i;
test2+=i;
}
int thd=clock();
for(int i=1;i<=100000001;++i){
test3+=i;
// test3<<=i;
}
int fh=clock();
for(register int i=1;i<=100000001;i=-~i){
test4+=i;
// test4<<=i;
}
int ff=clock();
for(int i=1;i<=100000001;i=-~i){
test5+=i;
// test5<<=i;
}
int sx=clock();
printf("%d %d %d %d %d",sc-fst,thd-sc,fh-thd,ff-fh,sx-ff);
}
以下为洛谷IDE测试情况
在c++98情况下,
输出为
155054 143962 156000 143969 155958
并稳定在附近
在c++11(c++14~20类似)情况下,
输出为
155055 135969 155999 135969 151968
并稳定在附近
$test2 $ o r or or t e s t 4 test4 test4 最优
可是在c++11 + O2情况下,
27068 28000 28000 24000 28000
27052 52000 28000 24000 28000
test2不稳定~~(氧中毒?)~~,test4最优
综上,写for循环还是
扫描二维码关注公众号,回复:
16957752 查看本文章
for(register int I=1;I<=N;I=-~I)
吧
Update at 2023/10/1
C++14/17/20 下 test4平均仍最优,但是出现波动
相比于卡常(lxl题除外) 还是老老实实优化算法吧!