简体   繁体   English

右移同样的速度与左移相同?

[英]test bit by right shift same speed as left shift?

Is it the same speed to do 它的速度是否相同

#define CHECK_BIT_BOOL(var,pos) ((var>>(pos)) & 1)

as

#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))

the goal is to NOT use BOOL macro like: 目标是不要像以下那样使用BOOL宏:

#define BOOL(x) (!(!(x)))

BOOL(CHECK_BIT(foo, 3));

it is nicer to do: CHECK_BIT_BOOL(foo,3); 它更好: CHECK_BIT_BOOL(foo,3);

general test bit question 一般测试位问题

Current C compilers are very smart in translating typical code into the best machine language. 当前的C编译器非常聪明地将典型代码转换为最佳机器语言。 Most of the time trying to outsmart the compiler will confuse it into generating dumb code. 大多数时候试图超越编译器会将它混淆为生成愚蠢的代码。

Modern CPUs are able to do more than one operation at a time, whatever time this uses up will probably be shadowed by other operations, and make no difference. 现代CPU一次可以执行多个操作,无论何时耗尽都可能被其他操作遮蔽,并且没有任何区别。 And CPUs are much faster than memory, most programs are more slowed down by memory access than computing. 和CPU比内存快很多 ,大多数程序更容易受到内存访问比计算放缓。

Your time programming is much more valuable than any gain in runtime you can get by such microoptimizations, unless the code runs thousands of times a day on millions of machines. 除非代码每天在数百万台机器上运行数千次,否则您的编程时间比通过此类微优化获得的运行时获得的价值更有价值。 Concentrate on simple, clean, obviosly right and understandable code. 专注于简单,干净,令人难以置信的正确和可理解的代码。 When reading it next week you'll be grateful. 下周阅读时,你会感激不尽。

If pos is a constant, then CHECK_BIT is likely to be marginally faster, as there's no need to do the shift at run time. 如果pos是常数,则CHECK_BIT可能稍微快一些,因为在运行时不需要进行移位。 Otherwise, both are likely to be the same. 否则,两者都可能是相同的。 But as you point out, you'll need to do more work after CHECK_BIT if you need to constrain the result to be zero or one. 但正如你所指出的,如果你需要将结果约束为零或一,你需要在CHECK_BIT之后做更多的工作。

This of course depends on your target platform and, if your performance requirements are strict enough to warrant worrying about the cost of a single processor instruction, you'll have to profile and measure the real performance on a real system. 这当然取决于您的目标平台,如果您的性能要求足够严格以保证担心单处理器指令的成本,您将必须分析和测量真实系统的真实性能。

CHECK_BIT_BOOL and CHECK_BIT are extremely fast if var and pos are not in memory but already in registers. 如果var和pos不在内存中但已经在寄存器中,则CHECK_BIT_BOOL和CHECK_BIT非常快。 Even if it is in memory - you cannot get it faster (if var is 1 byte, you could create array of 256*8 results and return result immediately by just returning results[var + 256*8] but it will be much slower than doing >> and &). 即使它在内存中 - 你也无法更快地获得它(如果var是1个字节,你可以创建256 * 8结果的数组并立即返回结果只返回结果[var + 256 * 8]但它会比做>>和&)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM