C++優化:把頻繁操作的成員變量局部化

當我們在類成員函數中頻繁操作類成員變量時(例如,在for循環中反覆調用成員變量),我們可以把該成員變量複製到成員函數中,成爲局部變量,幫助編譯器更好的優化循環體,因爲成員變量對編譯器來說更容易追蹤。

例如下面程序,在operator()的for循環中反覆調用成員變量m_i:

// main.cpp
#include <iostream>
#include "tbb/tbb.h"
using namespace std;
using namespace tbb;
#define NUM 100000000

class Body {
public:
    Body():m_i(1) {}
    ~Body() {}
    void operator()() {
        int sum = 0;
        for (int i = 0; i < NUM; i++) {
            sum += m_i;                 // 反覆調用成員變量m_i
        }
    }
int m_i;
};

int main(int argc, char** args) {
    tick_count start = tick_count::now();
    Body bd;
    bd();
    cout << "consume time is:" << (tick_count::now() - start).seconds() << endl;
    return 0;
}

執行時間大約爲0.38s。
這裏寫圖片描述

在operator()中把成員變量m_i複製到局部變量i上:

#include <iostream>
#include "tbb/tbb.h"
using namespace std;
using namespace tbb;
#define NUM 100000000

class Body {
public:
    Body():m_i(1) {}
    ~Body() {}
    void operator()() {
        int sum = 0;
        int i = m_i;
        for (int i = 0; i < NUM; i++) {
            sum += i;                    // 反覆調用局部變量i
        }
    }
int m_i;
};

int main(int argc, char** args) {
    tick_count start = tick_count::now();
    Body bd;
    bd();
    cout << "consume time is:" << (tick_count::now() - start).seconds() << endl;
    return 0;
}

執行時間大約爲0.35s,和沒有局部處理相比快了0.03s,這是一個較大的性能提高。
這裏寫圖片描述

發佈了27 篇原創文章 · 獲贊 26 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章