0

Ahoy friends. I'm writing some code using the PAWN language (C similar) but i need to optimize the run time. So i wan't to try to use bitwise operations here. I got my function to round integers but i need to rewrite it to take a little time less.

Can someone explain how to convert these operations into bitwise operations and why? And how can they optimize the run time of the program if they do exactly the same?

Thanks for your help!

stock round(num)
{
    new rem = num % 10;
    return rem >= 5 ? (num - rem + 10) : (num - rem);
}
FBDIMM
  • 1
  • 2
  • division not by a power of 2 can't be done quickly with bitwise operations. [Algorithm for Bitwise operation on Modulus for number of not a power of 2](https://stackoverflow.com/q/49949579/995714). However [division by a constant can be converted to multiplication by a multiplicative inverse](https://stackoverflow.com/q/41183935/995714) and the compiler will take care of that for you. Possible duplicates: [Divide by 10 using bit shifts?](https://stackoverflow.com/q/5558492/995714), [fast division/mod by 10^x](https://stackoverflow.com/q/2033210/995714) – phuclv Jan 30 '19 at 15:25
  • and you don't need a ternary operator like that. Possible duplicates: [Integer division rounding with negatives](https://stackoverflow.com/q/319880/995714), [Rounding integer division (instead of truncating)](https://stackoverflow.com/q/2422712/995714), [How to round up the result of integer division?](https://stackoverflow.com/q/17944/995714), [How to round up integer division and have int result](https://stackoverflow.com/q/7446710/995714) – phuclv Jan 30 '19 at 15:25
  • Possible duplicate of [Rounding integer division (instead of truncating)](https://stackoverflow.com/questions/2422712/rounding-integer-division-instead-of-truncating) – phuclv Jan 30 '19 at 15:26
  • oops the correct dupes are [Rounding up to the nearest multiple](https://stackoverflow.com/q/3407012/995714), [find the next multiple of 10 of any integer](https://stackoverflow.com/q/2403631/995714), [Rounding integers to nearest multiple of 10](https://stackoverflow.com/q/15154457/995714), [Rounding off a number to the next nearest multiple of 5](https://stackoverflow.com/q/44110606/995714). Again only powers of 2 are special [quick calculation of next multiple of 4](https://stackoverflow.com/q/2022179/995714), [Round off to multiple of 8](https://stackoverflow.com/q/1766535/995714) – phuclv Jan 31 '19 at 02:05

1 Answers1

1
(num + 5) / 10 * 10

would be hard to beat: check the assembly (especially the division) and let the compiler optimise to bitwise operations if it judges them to be faster. Your version has a branch which could cause the pipeline to dump on an incorrect branch prediction.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483