假設驗證數 m 的奇偶性:
- 一般會想到直接用求餘運算,即 m % 2;
- 用位運算也可以達到一樣的效果,即 m & 1;式子就是求二進制末尾的數是 0 還是 1;
二者的運算都是奇數返回1,偶數返回0;但是最近遇到一道題,在驗證的時候二者的運行速度差距比較大
(先說結果:位運算 優於 求餘運算),針對這個問題,我進行了測試,代碼如下:
測試編譯器:QT Creator自帶編譯器
#include <iostream>
using namespace std;
#include <time.h>
//分別進行了 求餘-位運算-求餘-位運算 4次計算;
//每次用了100萬個數,返回兩次求餘數和兩次位運算的平均值;
pair<double,double> testMod(){
double t_mod1,t_mod2,t_bit1,t_bit2;
//01模塊:求餘
clock_t start = clock();
//測試塊-----------
int arr1[500000];
for(int i = 0; i < 1000000; i++){
int m = i%2;
if(m == 0)
arr1[m/2] = m;
}
//------------
clock_t ends = clock();
t_mod1 = (double)(ends - start)/ CLOCKS_PER_SEC;
//02模塊:位運算
clock_t start2 = clock();
//測試塊-----------
int arr2[500000];
for(int i = 0; i < 1000000; i++){
int m = i&1;
if(m == 0)
arr2[m/2] = m;
}
//------------
clock_t ends2 = clock();
t_bit1 = (double)(ends2 - start2)/ CLOCKS_PER_SEC;
//03模塊:求餘
clock_t start3 = clock();
//測試塊-----------
int arr3[500000];
for(int i = 0; i < 1000000; i++){
int m = i%2;
if(m == 0)
arr3[m/2] = m;
}
//------------
clock_t ends3 = clock();
t_mod2 = (double)(ends3 - start3)/ CLOCKS_PER_SEC;
//04模塊:位運算
clock_t start4 = clock();
//測試塊-----------
int arr4[500000];
for(int i = 0; i < 1000000; i++){
int m = i&1;
if(m == 0)
arr4[m/2] = m;
}
//------------
clock_t ends4 = clock();
t_bit2 = (double)(ends4 - start4)/ CLOCKS_PER_SEC;
return pair<double,double>( (t_mod1+t_mod2)/2, (t_bit1+t_bit2)/2);
}
int main()
{
double mod_time = 0, bit_time = 0;
pair<double,double>res;
int times = 100; //測試次數
int win = 0;
for(int i = 0; i < times; i++){
res = testMod();
mod_time += res.first;
bit_time += res.second;
if(res.first > res.second)
win++;
}
cout<<"mod Time: "<<mod_time/times<<endl;
cout<<"bit Time: "<<bit_time/times<<endl;
cout<<"bit win: "<<win<<endl;
return 0;
}
測試時,若main函數中的 times = 1時,差距不明顯
mod Time: 0.0036635
bit Time: 0.0031245
bit win: 1
times = 10
mod Time: 0.00286435
bit Time: 0.0025851
bit win: 10
times = 100
mod Time: 0.00228572
bit Time: 0.00211616
bit win: 100
times = 1000
mod Time: 0.00221833
bit Time: 0.00208492
bit win: 996
可以看出,位運算總體還是優於求餘運算的。