我有一個圖像。每個像素都包含有關RGB強度的信息。現在我想總結這些頻道的信息,但我也想選擇哪個頻道的總和。 Straightforwad實施,這將是這樣的:在編譯時生成函數
int intensity(const unsiged char* pixel, bool red, bool green, bool blue){
return 0 + (red ? pixel[0] : 0) + (green ? pixel[1] : 0) + (blue ? pixel[2] : 0);
}
因爲我會調用這個函數,針對圖像的每個像素我要放棄所有條件。如果我可以。所以我想我一定要對每一個案件的函數:
std::function<int(const unsigned char* pixel)> generateIntensityAccumulator(
const bool& accumulateRChannel,
const bool& accumulateGChannel,
const bool& accumulateBChannel)
{
if (accumulateRChannel && accumulateGChannel && accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[0]) + static_cast<int>(pixel[1]) + static_cast<int>(pixel[2]);
};
}
if (!accumulateRChannel && accumulateGChannel && accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[1]) + static_cast<int>(pixel[2]);
};
}
if (!accumulateRChannel && !accumulateGChannel && accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[2]);
};
}
if (!accumulateRChannel && !accumulateGChannel && !accumulateBChannel){
return [](const unsigned char* pixel){
return 0;
};
}
if (accumulateRChannel && !accumulateGChannel && !accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[0]);
};
}
if (!accumulateRChannel && accumulateGChannel && !accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[1]);
};
}
if (accumulateRChannel && !accumulateGChannel && accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[0]) + static_cast<int>(pixel[2]);
};
}
if (accumulateRChannel && accumulateGChannel && !accumulateBChannel){
return [](const unsigned char* pixel){
return static_cast<int>(pixel[0]) + static_cast<int>(pixel[1]);
};
}
}
現在我可以用這個發電機進入圖像循環使用前和使用功能,不附加任何條件:
...
auto accumulator = generateIntensityAccumulator(true, false, true);
for(auto pixel : pixels){
auto intensity = accumulator(pixel);
}
...
但它是一個很大的寫這樣一個簡單的任務,我有一種感覺,有一個更好的方法來完成這個任務:例如讓編譯器爲我做一個骯髒的工作,併產生以上所有情況。有人能指引我朝着正確的方向嗎?
你有沒有經過上面的性能測試?我感到驚訝的是,在循環外部移動簡單的布爾測試應該非常重要,因爲處理器通常通過假設「與上次時間相同的結果」來優化分支... –
我承認我沒有 - 我只是假設指令條件會產生性能更好。我讀了關於分支預測(http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/),我想它會適用於我的情況。謝謝! – Amadeusz
我的意思是,我可能是錯的......我只是考慮在做任何太複雜的事情之前進行性能測試。 –