@reagentx/

# Find Crossover

## No description

Files
• main.py
• viz.png
main.py
```1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
```
```import timeit
import time

import pandas as pd

base = 2
power = 2
iterations = 100000

def generate_mult_func(n):
mult_steps = '*'.join(['q'] * n)
func_string = f'lambda q: {mult_steps}'  # Keep this so we can print later
return eval(func_string), func_string

exponent = lambda base, power: base ** power
multiply, func_string = generate_mult_func(power)

# Find initial speeds
multiply_speed = timeit.timeit('multiply(base)',
setup="from __main__ import base, multiply",
number=iterations)
exponent_speed = timeit.timeit('exponent(base, power)',
setup="from __main__ import base, power, exponent",
number=iterations)
math_pow_speed = timeit.timeit('math.pow(base, power)',
setup="from __main__ import base, power; import math",
number=iterations)

print('Starting speeds:')
print(f'Multiply: {multiply_speed*1000:0.2f} ms')
print(f'Exponent: {exponent_speed*1000:0.2f} ms')
print(f'math.pow: {math_pow_speed*1000:0.2f} ms')

# Save the data we can analyze later
data = {
'multiply': [multiply_speed],
'exponent': [exponent_speed],
'math.pow': [math_pow_speed],
'Power': [power]
}

t0 = time.time()
while exponent_speed >= multiply_speed:
# for i in range(1000):
# print(i)
power += 1
# Get the next multiply func
multiply, func_string = generate_mult_func(power)
assert(multiply(base) == exponent(base, power))

# Find new speeds
multiply_speed = timeit.timeit('multiply(base)',
setup="from __main__ import base, multiply",
number=iterations)
exponent_speed = timeit.timeit('exponent(base, power)',
setup="from __main__ import base, power, exponent",
number=iterations)
math_pow_speed = timeit.timeit('math.pow(base, power)',
setup="from __main__ import base, power; import math",
number=iterations)

# Add to our dict of data
data['multiply'].append(multiply_speed)
data['exponent'].append(exponent_speed)
data['math.pow'].append(math_pow_speed)
data['Power'].append(power)

print(f'\nCrossover found in {time.time() - t0:0.2} s:')
print(f'Base, power \t{base}, {power}')
print(f'Multiply time\t{multiply_speed*1000:0.2f} ms')
print(f'Exponent time\t{exponent_speed*1000:0.2f} ms')
print(f'math.pow time\t{math_pow_speed*1000:0.2f} ms')
print(f'Multiply func\t{func_string}')

# Handle viz
df = pd.DataFrame.from_dict(data)
df.set_index('Power', drop=True, inplace=True)
df.to_csv('data.csv', float_format='%.40f')
plot = df.plot(title=f'Executution time (s) for {iterations:,} iterations').get_figure()
plot.savefig('viz.png')
```