測試“求餘” 與 “位與” 的效率
測試環境:
1、操作系統: Windows XP Professional SP2
2、CPU: Intel Celeron 3.06GHz
3、內存: 248M
循環次數:
各40億次
測試代碼如下:
//代碼開始
//******************************************************
#include <iostream>
using namespace std;
#include <time.h>
#include <windows.h>
int main( int argc, char *argv[ ], char *envp[ ] )
{
clock_t t1, t2;
t1 = ::GetTickCount();
for(unsigned long i = 0; i < 4e9; i++)
{
if(i%2==0);//求餘運算
}
t2 = ::GetTickCount();
cout << "求餘執行"<< i <<"次時間:" << t2 - t1 << "毫秒" << endl;
t2 = t1 = 0;
Sleep(50);
t1 = ::GetTickCount();
for(i = 0; i < 4e9; i++)
{
if(i&1==0);//位與運算
}
t2 = ::GetTickCount();
cout << "位與執行"<< i <<"次時間:" << t2 - t1 << "毫秒" << endl;
return 0;
}
//******************************************************
//代碼結束
程序執行3次結果如下:
求餘執行4000000000次時間:113110毫秒
位與執行4000000000次時間:113188毫秒
求餘執行4000000000次時間:113093毫秒
位與執行4000000000次時間:113141毫秒
求餘執行4000000000次時間:113109毫秒
位與執行4000000000次時間:113141毫秒
從結果可判斷:“求餘” 與 “位與”執行效率相差無幾。