Skip to content
Advertisement

Fastest way to round random numbers in python

I want to generate random numbers up to certain precision, one at a time (so I am not looking for a vectorized solution).

I found a method in this QnA on stackoverflow, and it gave me these benchmarks as promised. The method is definitely is almost twice as fast. Now, here’s what is puzzling me.

JavaScript

Why is the above method slower when I’m using variables? It regains the lost speed when I pass the randomly generated number directly. What am I missing?

In my code, since I require rounding at multiple places, I would like it wrapped in a function as follows. I understand that there is a small cost associated with the function call, but I don’t think that’s whats costing the bulk of the increased time. This answer says, it still ought to be faster than the standard round() function of python.

JavaScript

I would prefer not having a global variable in my code, but let’s say I concede to this requirement, but the performance gain is smaller, than using the formula without variables.

So, the final question would be, which method would be most beneficial for me to use? There is only a gain of 100-150ns to switching to a function that requires a global variable. Or is there someway that can be faster.

Advertisement

Answer

The Python byte-compiler “knows” how numbers work, and it uses this knowledge to optimise things where it can. You can use the dis module to see what’s happening.

For example, your first “fast” example:

JavaScript

actually does:

JavaScript

i.e. it knows what 0.5192853551955484*(10**5)+0.5 evaluates to and does it when compiling the byte code. If you have pr as a parameter it can’t do that, so has to do more work when running the code.

To answer the “what would be best” question, maybe something like:

JavaScript

can be benchmarked with:

JavaScript

giving ~160ns per loop, while:

JavaScript

run in ~500 and ~250ns. Didn’t realise that int vs float exponentiation was so different!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement