I would understand if numpy was smart enough to see that array % 1
does not do anything, and that runtime is independent of the input. I would also understand if runtime was longer for larger numbers, maybe because dividing a large number takes longer (compare Why is floating-point division in Python faster with smaller numbers?). But why does array % 1
run longer for smaller numbers?
from timeit import timeit
import numpy as np
a1 = np.random.randint(500, size=20_000_000, dtype=np.int32) - 250
a2 = np.random.randint(20_000_000, size=20_000_000, dtype=np.int32) - 250
print(timeit(lambda: a1 % 1, number=5))
print(timeit(lambda: a2 % 1, number=5))
print(timeit(lambda: a1 % 1, number=5))
print(timeit(lambda: a2 % 1, number=5))
Output:
0.4755298000000039
0.19294559999980265
0.460197700000208
0.19560679999995045