为什么 CPU 分支指令很慢? [英] Why is a CPU branch instruction slow?

查看:26
本文介绍了为什么 CPU 分支指令很慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我开始编程以来,我到处阅读,不惜一切代价避免浪费分支.

Since I started programming, I have read in every place to avoid wasteful branches at all costs.

那很好,虽然没有一篇文章解释我为什么要这样做.当 CPU 解码分支指令并决定执行跳转时,究竟会发生什么?什么是使它比其他指令(如加法)慢的东西"?

That's fine, although none of the articles explained why I should do this. What exactly happens when the CPU decodes a branch instruction and decides to do a jump? And what is the "thing" that makes it slower than other instructions (like addition)?

推荐答案

分支指令本身并不比任何其他指令慢.

A branch instruction is not inherently slower than any other instruction.

然而,您听说应该避免分支的原因是因为现代 CPU 遵循 流水线架构.这意味着有多个顺序指令同时执行.但是,只有在每个周期都能够从内存中读取下一条指令时,才能充分利用流水线,这意味着它需要知道要读取条指令.

However, the reason you heard that branches should avoided is because modern CPUs follow a pipeline architecture. This means that there are multiple sequential instructions being executed simultaneously. But the pipeline can only be fully utilised if it's able to read the next instruction from memory on every cycle, which in turn means it needs to know which instruction to read.

条件分支上,它通常不提前知道将采用哪条路径.因此,当发生这种情况时,CPU 必须停止,直到决策得到解决,并丢弃流水线中分支指令后面的所有内容.这会降低利用率,从而降低性能.

On a conditional branch, it usually doesn't know ahead of time which path will be taken. So when this happens, the CPU has to stall until the decision has been resolved, and throws away everything in the pipeline that's behind the branch instruction. This lowers utilisation, and therefore performance.

这就是诸如分支预测和<存在一个 href="http://en.wikipedia.org/wiki/Branch_delay_slot" rel="noreferrer">分支延迟槽.

这篇关于为什么 CPU 分支指令很慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆