天天看點

代碼說話:整數位操作比除法/取餘…

#include <iostream>

#include <string>

#include <ctime>

#include <sys/timeb.h>

#include <boost/scoped_array.hpp>

using namespace std;

#define TIMES 100000000

time_t getms()

{

      timeb tb;

      ftime(&tb);

      return (int)(tb.time*1000 + tb.millitm);

}

int main()

{

      boost::scoped_array<int> data(new int[TIMES]);

      boost::scoped_array<int> result1(new int[TIMES]);

      boost::scoped_array<int> result2(new int[TIMES]);

      boost::scoped_array<int> result3(new int[TIMES]);

      for (int i = 0; i < TIMES; ++ i)

      {

            data[i] = i;

      }

      {

            time_t oldtime = getms();

            for (int i = 0; i < TIMES; ++ i)

            {

                  result1[i] = (data[i] & 0x0F);                       

            }

            time_t newtime = getms();

            cout << (newtime - oldtime) << endl;

      }     

      {

            time_t oldtime = getms();

            for (int i = 0; i < TIMES; ++ i)

            {

                  result2[i] = data[i];

                  result2[i] %= 16;

            }

            time_t newtime = getms();

            cout << (newtime - oldtime) << endl;

      }

      {

            time_t oldtime = getms();

            for (int i = 0; i < TIMES; ++ i)

            {

                  result2[i] = data[i];

                  result2[i] %= 15;

            }

            time_t newtime = getms();

            cout << (newtime - oldtime) << endl;

      }

      while (true)

      {

            int j;

            cin >> j;

            if (j == 0)

            {

                  return 0;

            }

            {

                  time_t oldtime = getms();

                  for (int i = 0; i < TIMES; ++ i)

                  {

                        result3[i] = data[i];

                        result3[i] %= j;                 

                  }

                  time_t newtime = getms();

                  cout << (newtime - oldtime) << endl;

            }     

      }

}

==========================================

結果(運作次數1億次):

219              // 使用位操作

234              // 用取模操作%,但是被編譯器優化成位操作,看彙編代碼很明顯

500              // mod 15, 無法優化,乖乖用除法去

13                // 我的輸入,接下來做一億次的mod 13

496             // 時間

15                // 我的輸入,接下來做一億次的mod 15

495             // 時間

16                // 我的輸入,接下來做一億次的mod 16

485              // 哈哈,現在沒法優化了吧~乖乖做除法

17                // mod 17

484              // 時間

============================================

分析:

      整數位操作比除、模快一些,用上述資料大概2倍多(我也測試了256和65536作為除數)。對于常量來說,編譯器會優化,試圖用位操作替換。不過如果不是2的整數倍,也隻能乖乖做除法去。如果想看有沒有優化,檢視彙編代碼即可。

      大部分時候這種方法帶來的性能提升并不明顯,不過如果是關鍵路徑的話,可能還是有用武之地。