设置或重置给定位而不分支 [英] Set or Reset a given bit without branching

查看:87
本文介绍了设置或重置给定位而不分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一次采访中,他们问我:您如何设置或重置?这是一个非常简单的问题,我回答了.

in one interview, they asked me, How do you set or reset a bit? This is a very simple question and I answered that.

之后他们问我,without branching.我不知道什么是分支. 我寻找那个,我来到这里 http://graphics.stanford.edu/~seander/bithacks.html

After that they asked me, do that without branching. I dont know what is branching. I search for that and I came here http://graphics.stanford.edu/~seander/bithacks.html

但是仍然没有得到分支和非分支的概念. 请说明Branching.

But still not getting concept of branching and non-branching. Please explain Branching.

推荐答案

分支意味着CPU执行的指令包含条件跳转.择一选择.这可能意味着iffor循环,while循环,switch?:或基于布尔值做出决定的事物.

Branching means that the instructions the cpu executes contain a conditional jump. An either-or choice. Which could mean an if, a for-loop, while-loop, switch, ?: or something that makes a decision based on a boolean.

人们经常忘记的一类分支也使布尔运算符和可能(但不一定在所有CPU上)求值达到真值的事物短路,因此int foo; ...; foo = !foo;将成为某些CPU上的分支,但并非全部(不适用于x86).

One class of branches that people often forget are also short-circuiting boolean operators and possibly (but not necessarily on all CPUs) things that evaluate to truth values, so int foo; ...; foo = !foo; will be a branch on some CPUs, but not all (not on x86).

所以要设置一点:

i |= (1 << bit);

重设一点:

i &= ~(1 << bit);

切换一下:

i ^= (1 << bit);

没有分支.我实际上看不到如何使它变得如此复杂以致不得不使用分支.

No branches. I actually don't see how to make this so complicated to have to use a branch.

某人可能要担心分支的原因是分支预测. 请参阅此问题和解答一个很好的解释,说明为什么如此重要.

The reason why someone might want to worry about branches is branch prediction. See this question and answer for an excellent explanation of why it matters.

这篇关于设置或重置给定位而不分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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