📚 The CoCalc Library - books, templates and other resources
License: OTHER
""" Code from Think Complexity, 2nd Edition, by Allen Downey.12Available from http://greenteapress.com34Copyright 2019 Allen B. Downey.5MIT License: https://opensource.org/licenses/MIT6"""78import os9import matplotlib.pyplot as plt1011def etime():12"""Measures user and system time this process has used.1314Returns the sum of user and system time."""15user, sys, chuser, chsys, real = os.times()16return user+sys1718def time_func(func, n):19"""Run a function and return the elapsed time.2021func: function22n: problem size2324returns: user+sys time in seconds25"""26start = etime()27func(n)28end = etime()29elapsed = end - start30return elapsed3132def run_timing_test(func, max_time=1):33"""Tests the given function with a range of values for n.3435func: function object3637returns: list of ns and a list of run times.38"""39ns = []40ts = []41for i in range(10, 28):42n = 2**i43t = time_func(func, n)44print(n, t)45if t > 0:46ns.append(n)47ts.append(t)48if t > max_time:49break5051return ns, ts5253def fit(ns, ts, exp=1.0, index=-1):54"""Fits a curve with the given exponent.5556ns: sequence of problem sizes57ts: sequence of times58exp: exponent of the fitted curve59index: index of the element the fitted line should go through6061returns: sequence of fitted times626364"""65# Use the element with the given index as a reference point,66# and scale all other points accordingly.67nref = ns[index]68tref = ts[index]6970tfit = []71for n in ns:72ratio = n / nref73t = ratio**exp * tref74tfit.append(t)7576return tfit7778def plot_timing_test(ns, ts, label='', color='blue', exp=1.0, scale='log'):79"""Plots data and a fitted curve.8081ns: sequence of n (problem size)82ts: sequence of t (run time)83label: string label for the data curve84color: string color for the data curve85exp: exponent (slope) for the fitted curve86"""87tfit = fit(ns, ts, exp)88fit_label = 'exp = %d' % exp89plt.plot(ns, tfit, label=fit_label, color='0.7', linestyle='dashed')90plt.plot(ns, ts, 'o-', label=label, color=color, alpha=0.7)91plt.xlabel('Problem size (n)')92plt.ylabel('Runtime (seconds)')93plt.xscale(scale)94plt.yscale(scale)95plt.legend()969798