classification
Title: random.uniform 2x slower than inline implementation
Type: performance Stage: resolved
Components: C API Versions: Python 3.9
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Scott Norton, rhettinger, serhiy.storchaka
Priority: normal Keywords:

Created on 2020-12-21 15:25 by Scott Norton, last changed 2020-12-21 17:35 by rhettinger. This issue is now closed.

Messages (3)
msg383532 - (view) Author: Scott Norton (Scott Norton) Date: 2020-12-21 15:25
The library function random.uniform takes about twice as long as a manual inline implementation (Python 3.9.1).

>>> import timeit
>>> timeit.timeit('3 + (8 - 3) * random.random()', 'import random')
0.1540887290000228
>>> timeit.timeit('a + (b - a) * random.random()', 'import random\na = 3\nb = 8')
0.17950458899986188
>>> timeit.timeit('random.uniform(3, 8)', 'import random')  # does the call/return really add that much overhead?
0.31145418699999894
msg383534 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2020-12-21 15:39
Yes, calling functions in Python has some overhead. It is not specific to random.uniform().
msg383540 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2020-12-21 17:35
> does the call/return really add that much overhead?

Yes, it does.

$ python3.9 -m timeit -s 'x=3.5' 'x**2'
5000000 loops, best of 5: 63.5 nsec per loop
$ python3.9 -m timeit -s 'x=3.5' -s 'f=lambda x: x**2' 'f(x)'
2000000 loops, best of 5: 136 nsec per loop
History
Date User Action Args
2020-12-21 17:35:04rhettingersetstatus: open -> closed
resolution: not a bug
messages: + msg383540

stage: resolved
2020-12-21 15:39:26serhiy.storchakasetnosy: + rhettinger, serhiy.storchaka
messages: + msg383534
2020-12-21 15:25:39Scott Nortoncreate