Stimmt. Das habe ich nicht bedacht. Allerdings sind bei mir die Zahlen für die Modulo-Variante noch immer besser (wenn auch nicht mehr so drastisch):
Code: Alles auswählen
#!/usr/bin/env python3
from time import time
from random import randint, shuffle
from statistics import mean, stdev
N = 10_000
REPETITIONS = 100
LOWER = 1
UPPER = 1_000_000_000
def string_based(s):
return s[-1] in ('0', '5') and len(s) > 2
def modulo_based(n):
return n % 5 == 0 and n > 99
def decimal_based(n):
if n % 10 not in (0, 5):
return False
i = 0
k = n
while k > 0:
i += 1
k //= 10
if i > 2:
return False
return True
ALGORITHMS = [
('string comparison', string_based),
('modulo calculation', modulo_based),
('decimal position', decimal_based)
]
def random_numbers(n, lower, upper):
divisible = set()
indivisible = set()
while len(divisible) < n or len(indivisible) < n:
x = randint(lower, upper)
if len(divisible) < n and x % 5 in (0, 5):
divisible.add(x)
elif len(indivisible) < n:
indivisible.add(x)
return tuple(divisible), tuple(indivisible)
def main():
print('N:', N)
print('Range:', LOWER, UPPER)
print('Repetitions:', REPETITIONS)
results = dict()
algorithms = ALGORITHMS
for _ in range(REPETITIONS):
divisible, indivisible = random_numbers(N, LOWER, UPPER)
for label, function in ALGORITHMS:
if label == 'string comparison':
divisible_temp = [str(i) for i in divisible]
indivisible_temp = [str(i) for i in indivisible]
else:
divisible_temp = divisible
indivisible_temp = indivisible
t1 = time()
for group in (divisible_temp, indivisible_temp):
for number in group:
result = function(number)
t2 = time()
results.setdefault(label, [])
results[label].append(t2 - t1)
# shuffle last, so order is mainted in modern python
shuffle(algorithms)
print()
for label, durations in results.items():
print(label, '(mean):', mean(durations))
print(label, '(sd):', stdev(durations))
print(label, '(sum):', sum(durations))
print()
if __name__ == '__main__':
main()
Code: Alles auswählen
$ ./fives.py :(
N: 10000
Range: 1 1000000000
Repetitions: 100
string comparison (mean): 0.0033177709579467773
string comparison (sd): 0.00032582172245825377
string comparison (sum): 0.33177709579467773
modulo calculation (mean): 0.002630734443664551
modulo calculation (sd): 0.0005114850119894751
modulo calculation (sum): 0.2630734443664551
decimal position (mean): 0.0063778114318847655
decimal position (sd): 0.0006249521611702232
decimal position (sum): 0.6377811431884766