Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Faster than bit shifting macros?

Status
Not open for further replies.

RbgoWeb

Programmer
Apr 10, 2002
91
0
0
NL
I'm experimenting with macros that can read and write parts of basic types. Normal bit shifts and AND masks are used a lot. But I thought that with help of a little structure operants are only casted and assigned and things may run a little faster when loads of data need processing.
Can someone tell me if this approach would have higher performance than the usuall approach? Do type casts cost performance?

typedef struct _B2 { BYTE _0, _1; } B2;

//packs two bytes into a word
#define B2PK(w, b1, b0) { (((B2 *)&w)->_1 = (b1)); (((B2 *)&w)->_0 = (b0)); }

//Reads words
#define B2R0(w) (((B2 *)&w)->_0)
#define B2R1(w) (((B2 *)&w)->_1)
//Writes words
#define B2W0(w, b0) (((B2 *)&w)->_0 = (b0))
#define B2W1(w, b1) (((B2 *)&w)->_1 = b1))
 
> Can someone tell me if this approach would have higher performance than the usuall approach?
Seems doubtful - all those pointer accesses look expensive

Why are you using a structure in the first place? I would be using an unsigned short to store two bytes, and using something like &, |, << and >> to extract and insert bytes

> Do type casts cost performance?
Depends - for example and int to a float takes some work.
Casting from one pointer type to another is fairly transparent on the usual desktop machines (I think). However, it is generally best avoided - casting Type1* into Type2* can lead to things like bus errors (trying to access mis-aligned data).

> #define B2R0(w)
What sort of 'w' are you passing to this function?
If w is of type B2, why bother with all the pointer / cast / dereference.
 
casting words into bytes and vice versa should cost nothing. It's just a matter of addressing, and the compiler should be able to handle that without any extra work. Shifting definitely costs (though not a lot).
On a 32 bit system if you are worried about performance, though, you should not be using words at all. Direct manipulation of a word in 32 bit code needs an operand size prefix on the op code, and this is a costly thing.
Masking is not free, but it is dirt cheap, ands being amongst the fastest and least offensive of all processor operations.
 
I submitted this thread in two forums at once. Sorry, but I'll continue on the other one in C++: Microsoft.
I won't do it again. =)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top