Skip to content

Instantly share code, notes, and snippets.

@LiYChristopher
Created April 12, 2016 03:51
Show Gist options
  • Save LiYChristopher/968cd4c269a120aa1e568a8a33372350 to your computer and use it in GitHub Desktop.
Save LiYChristopher/968cd4c269a120aa1e568a8a33372350 to your computer and use it in GitHub Desktop.
A simple plot depicting the speeds of different Python operations to achieve results of this task - list of squares of an array of numbers
import timeit
import matplotlib
from matplotlib import pyplot as plt
comp_setup = '''def comp_time(num):
return [i**2 for i in range(num)]
'''
loop_setup = '''def loop_time(num):
res = []
for i in range(num):
res.append(i**2)
return res
'''
map_setup = '''def map_time(num):
return map(lambda x: x**2, range(num))
'''
# list_comp
lc_ten = min(timeit.repeat("comp_time({})".format(10),
setup=comp_setup, number=10))
lc_hundred = min(timeit.repeat("comp_time({})".format(100),
setup=comp_setup, number=100))
lc_thousand = min(timeit.repeat("comp_time({})".format(1000),
setup=comp_setup, number=100))
lc_ten_thousand = min(timeit.repeat("comp_time({})".format(10000),
setup=comp_setup, number=100))
lc_hundred_thousand = min(timeit.repeat("comp_time({})".format(100000),
setup=comp_setup, number=100))
# loop_comp
nl_ten = min(timeit.repeat("comp_time({})".format(10),
setup=comp_setup, number=10))
nl_hundred = min(timeit.repeat("loop_time({})".format(100),
setup=loop_setup, number=100))
nl_thousand = min(timeit.repeat("loop_time({})".format(1000),
setup=loop_setup, number=100))
nl_ten_thousand = min(timeit.repeat("loop_time({})".format(10000),
setup=loop_setup, number=100))
nl_hundred_thousand = min(timeit.repeat("loop_time({})".format(100000),
setup=loop_setup, number=100))
# map
map_ten = min(timeit.repeat("comp_time({})".format(10),
setup=comp_setup, number=100))
map_hundred = min(timeit.repeat("map_time({})".format(100),
setup=map_setup, number=100))
map_thousand = min(timeit.repeat("map_time({})".format(1000),
setup=map_setup, number=100))
map_ten_thousand = min(timeit.repeat("map_time({})".format(10000),
setup=map_setup, number=100))
map_hundred_thousand = min(timeit.repeat("map_time({})".format(100000),
setup=map_setup, number=100))
# Plotting Data
plt.plot([10, 100, 1000, 10000, 100000], [nl_ten, nl_hundred, nl_thousand, nl_ten_thousand, nl_hundred_thousand])
plt.plot([10, 100, 1000, 10000, 100000], [lc_ten, lc_hundred, lc_thousand, lc_ten_thousand, lc_hundred_thousand])
plt.plot([10, 100, 1000, 10000, 100000], [map_ten, map_hundred, map_thousand, map_ten_thousand, map_hundred_thousand])
plt.title('Square of Numbers - Normal Loop, List Comprehension and Map')
plt.xlabel('Size of Input')
plt.ylabel('Runtime in Seconds')
plt.legend(['Normal Loop', 'List Comprehension', 'Map'], loc='upper left')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment