一般餘數運算最直接想到的是使用%,得到數值餘數。
可以利用2進制的&運算的特性達到取餘數的效果。
原理說明如下:
22 取 8的餘數會得到 6
然而 22 其 2進制為10110(2)
將其二進制與 7 進行 & 運算可以得到相同的結果:
10110
& 111
110
110 (2) 恰恰是 6 。
因此當取餘數為2的次方數時,皆可以透過&運算進行代替。
以下利用C++程式進行測試,測試其效能差異,程式碼如下:
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <time.h> #include <math.h> #define MAG 1000000 using namespace std; void time_start(); void time_end(char*); double START,END; int main(){ int a = 9949816583; int m = 8; int b = 7; int c = 0; time_start(); for (int i=1;i<=MAG;i++) c += a % m; time_end("% , "); cout << c << endl; c = 0; time_start(); for (int i=1;i<=MAG;i++) c += a & b; time_end("& , "); cout << c << endl; return 0; } void time_start(){ START = clock(); } void time_end(char *str){ END = clock(); cout << endl << str << "進行運算所花費的時間:" << (END - START) / CLOCKS_PER_SEC << " S" << endl; }
實際測試結果如下,根據實驗結果,效能提升效果非常細微,幫助不是很大。
但是測試過程中而外發現,
當數值過大的時候,取%的運算會出現溢位,
而&運算則能正常計算。
文章標籤
全站熱搜