Open
Description
Current problem
Following advice of R1730 consider-using-min-builtin, R1731 consider-using-max-builtin inside a for or a while loop will degrade performance of factor more than 3.
This is illustrated by the following example:
from random import randint
from sys import maxsize
from time import time
print('preparing\n')
values = []
for _ in range(2000000):
values.append(randint(1243, 2001245))
min_a = maxsize
min_b = maxsize
max_a = 0
max_b = 0
max_c = 0
tim_amin = 0.0
tim_amax = 0.0
tim_bmin = 0.0
tim_bmax = 0.0
print('type\ttotal time needed\tvalue')
start = time()
for i in values:
if i < min_a:
min_a = i
tim_amin = time()-start
print(f'min_a\t{tim_amin}\t{min_a}')
start = time()
for i in values:
if i > max_a:
max_a = i
tim_amax = time()-start
print(f'max_a\t{tim_amax}\t{max_a}')
start = time()
for i in values:
min_b = min(i, min_b)
tim_bmin = time()-start
print(f'min_b\t{tim_bmin}\t{min_b}')
start = time()
for i in values:
max_b = max(max_b, i)
tim_bmax = time()-start
print(f'max_b\t{tim_bmax}\t{max_b}')
print(f'\nspeedups {tim_bmin/tim_amin} and {tim_bmax/tim_amax}')
the output is
preparing
type total time needed value
min_a 0.0997917652130127 1243
max_a 0.09552979469299316 2001245
min_b 0.30522990226745605 1243
max_b 0.3029053211212158 2001245
speedups 3.0586682339561877 and 3.1707942228356223
Desired solution
The following suggestions to implement:
a) do not give this suggestion for assigning min() or max() to one of its arguments in a loop
or
b) this suggestion is given but with a performance warning
and additionally
- performance warning is givven when assigning min() or max() to one of its arguments in a loop
Additional context
No response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment