|
|
|
|
|
by tombert
464 days ago
|
|
I started using LMAX Disruptor for some projects. One quirk with Disruptor is that the queue size always has to be an exponent of two. I wanted to make sure that I always have at least enough room for any size and I didn't want to manually compute, so I wrote this: var actualSize = Double.valueOf(Math.pow(2, Math.ceil(Math.log(approxSize) / Math.log(2)))).intValue();
A bit much for a single line, but just using some basic log rules in order to the correct exponent. I learned all this in high school, but some of my coworkers thought I was using this amazing, arcane bit of math that had never been seen before. I guess they never use log outside of Big-O notation. |
|
(Integer.highestOneBit, also known as “isolate leftmost bit”, “most significant one”, or the like, essentially has to be a primitive to be efficient, unlike its counterpart for the lowest bit, x&-x. The actual CPU instruction is usually closer to Integer.numberOfLeadingZeros, but that’s just a bitshift away.)