[英]Cache miss penalty on branching
我想知道用2個乘法代替分支是否更快(由於高速緩存未命中罰款)?
這是我的情況:
float dot = rib1.x*-dir.y + rib1.y*dir.x;
if(dot<0){
dir.x = -dir.x;
dir.y = -dir.y;
}
我正在嘗試將其替換為:
float dot = rib1.x*-dir.y + rib1.y*dir.x;
int sgn = (dot < 0.0) - (0.0 < dot ); //returns -1 or 1 (no branching here, tested)
dir.x *= sgn;
dir.y *= sgn;
乘法的成本取決於幾個因素,是使用32位還是64位浮點數,以及是否啟用SSE。 根據此消息來源,兩個float乘法的成本為10個周期: http : //www.agner.org/optimize/instruction_tables.pdf
分支機構的成本還取決於幾個因素。 根據經驗,不必擔心代碼中的分支。 分支預測器在CPU上的確切行為將定義性能,但是在這種情況下,您應該期望分支充其量是不可預測的,因此這很可能導致許多分支預測錯誤。 根據此消息來源,分支錯誤預測的成本為10到30個周期: http : //valgrind.org/docs/manual/cg-manual.html
任何人都可以在此處提供的最佳建議是進行概要分析和測試。 我猜想在現代的Core i7上, if the range of input varies sufficiently as to cause sufficient branch mispredictions as to outweigh the cost of the additional multiplication
, if the range of input varies sufficiently as to cause sufficient branch mispredictions as to outweigh the cost of the additional multiplication
兩個乘法應該比分支更快。
假設未命中率為50%,則分支的成本平均為15個周期(30 * 0.5),浮點mul的成本為10個周期。
編輯 :添加了鏈接,更新了估計的教學成本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.