该文章用实际代码测试 x/2 与 x>>1 的速度。
注:本测试只能在不开 O2 的情况下进行。
测试代码
编译选项:-std=c++14 -Wall -Wextra
代码:
#include<iostream>
#include<ctime>
const int N=4e8,MOD=1e9;
int a[N];
int main(){
srand((unsigned)time(NULL));
for(int i=1;i<=N;++i)
a[i]=(rand()*1ll*rand())%MOD;
clock_t a_start=clock();// /2
for(int i=1;i<=N;++i)
a[i]/2;
clock_t a_end=clock();
double a_time_used=static_cast<double>(a_end-a_start)/CLOCKS_PER_SEC;
printf("time used(/2):%.3lfs\n",a_time_used);
clock_t b_start=clock();// >>1
for(int i=1;i<=N;++i)
a[i]>>1;
clock_t b_end=clock();
double b_time_used=static_cast<double>(b_end-b_start)/CLOCKS_PER_SEC;
printf("time used(>>1):%.3lfs\n",b_time_used);
return 0;
}测试结果
| 测试 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 总时间 | 平均时间 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
x/2 的时间/s | ||||||||||||
x>>1 的时间/s |
总结
x>>1 比 x/2 速度快,且更加稳定。建议使用 x>>1。