简体   繁体   中英

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:

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

BOOL(CHECK_BIT(foo, 3));

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

general test bit question

Current C compilers are very smart in translating typical code into the best machine language. 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. And CPUs are much faster than memory, most programs are more slowed down by memory access than computing.

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. 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.

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. 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 &).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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