Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

c - fast convert double to uint64_t in thread safe way

I have the below function that I call in a parallel loop. I have declared the union inside the below function for thread safety. The issue is that doing so slow things a lot. My question is whether there is a way to turn the double into an uin64_t (the same way as union does) but in a faster way? Thank you.

uint64_t flip(double d) {
  union {double d; uint64_t u64;} u;
  u.d = d;
  return u.u64 ^ (-(u.u64 >> 63) | 0x8000000000000000ULL);
}

I am using gcc to compile the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You might try re-doing this as a macro to eliminate the call and return overhead for the function:

#define DOUBLE_TO_UINT64(d) ((*(uint64_t *)(&(d))) ^ (-( (*(uint64_t *)(&(d))) >> 63) | 0x8000000000000000ULL))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...