mirror of
https://github.com/python/cpython.git
synced 2025-10-08 16:11:51 +00:00
Hoist the float conversion out of the inner loop. (GH-10430)
Currently, the *n* and *total* variables get converted to floats each time they are multiplied by random(). This minor tweak does the conversion just once and gets a small speedup (approx 3%).
This commit is contained in:
parent
cf5863faab
commit
0a18e0510a
1 changed files with 2 additions and 1 deletions
|
@ -375,6 +375,7 @@ class Random(_random.Random):
|
||||||
if cum_weights is None:
|
if cum_weights is None:
|
||||||
if weights is None:
|
if weights is None:
|
||||||
_int = int
|
_int = int
|
||||||
|
n += 0.0 # convert to float for a small speed improvement
|
||||||
return [population[_int(random() * n)] for i in range(k)]
|
return [population[_int(random() * n)] for i in range(k)]
|
||||||
cum_weights = list(_itertools.accumulate(weights))
|
cum_weights = list(_itertools.accumulate(weights))
|
||||||
elif weights is not None:
|
elif weights is not None:
|
||||||
|
@ -382,7 +383,7 @@ class Random(_random.Random):
|
||||||
if len(cum_weights) != n:
|
if len(cum_weights) != n:
|
||||||
raise ValueError('The number of weights does not match the population')
|
raise ValueError('The number of weights does not match the population')
|
||||||
bisect = _bisect.bisect
|
bisect = _bisect.bisect
|
||||||
total = cum_weights[-1]
|
total = cum_weights[-1] + 0.0 # convert to float
|
||||||
hi = n - 1
|
hi = n - 1
|
||||||
return [population[bisect(cum_weights, random() * total, 0, hi)]
|
return [population[bisect(cum_weights, random() * total, 0, hi)]
|
||||||
for i in range(k)]
|
for i in range(k)]
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue