Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132923 views
License: OTHER
1
""" Code from Think Complexity, 2nd Edition, by Allen Downey.
2
3
Available from http://greenteapress.com
4
5
Copyright 2019 Allen B. Downey.
6
MIT License: https://opensource.org/licenses/MIT
7
"""
8
9
import os
10
import matplotlib.pyplot as plt
11
12
def etime():
13
"""Measures user and system time this process has used.
14
15
Returns the sum of user and system time."""
16
user, sys, chuser, chsys, real = os.times()
17
return user+sys
18
19
def time_func(func, n):
20
"""Run a function and return the elapsed time.
21
22
func: function
23
n: problem size
24
25
returns: user+sys time in seconds
26
"""
27
start = etime()
28
func(n)
29
end = etime()
30
elapsed = end - start
31
return elapsed
32
33
def run_timing_test(func, max_time=1):
34
"""Tests the given function with a range of values for n.
35
36
func: function object
37
38
returns: list of ns and a list of run times.
39
"""
40
ns = []
41
ts = []
42
for i in range(10, 28):
43
n = 2**i
44
t = time_func(func, n)
45
print(n, t)
46
if t > 0:
47
ns.append(n)
48
ts.append(t)
49
if t > max_time:
50
break
51
52
return ns, ts
53
54
def fit(ns, ts, exp=1.0, index=-1):
55
"""Fits a curve with the given exponent.
56
57
ns: sequence of problem sizes
58
ts: sequence of times
59
exp: exponent of the fitted curve
60
index: index of the element the fitted line should go through
61
62
returns: sequence of fitted times
63
64
65
"""
66
# Use the element with the given index as a reference point,
67
# and scale all other points accordingly.
68
nref = ns[index]
69
tref = ts[index]
70
71
tfit = []
72
for n in ns:
73
ratio = n / nref
74
t = ratio**exp * tref
75
tfit.append(t)
76
77
return tfit
78
79
def plot_timing_test(ns, ts, label='', color='blue', exp=1.0, scale='log'):
80
"""Plots data and a fitted curve.
81
82
ns: sequence of n (problem size)
83
ts: sequence of t (run time)
84
label: string label for the data curve
85
color: string color for the data curve
86
exp: exponent (slope) for the fitted curve
87
"""
88
tfit = fit(ns, ts, exp)
89
fit_label = 'exp = %d' % exp
90
plt.plot(ns, tfit, label=fit_label, color='0.7', linestyle='dashed')
91
plt.plot(ns, ts, 'o-', label=label, color=color, alpha=0.7)
92
plt.xlabel('Problem size (n)')
93
plt.ylabel('Runtime (seconds)')
94
plt.xscale(scale)
95
plt.yscale(scale)
96
plt.legend()
97
98