Instantly share code, notes, and snippets.

Embed
What would you like to do?
Analysis of Comprehension Optimization
from optimize_comprehensions import optimize_comprehensions
import numpy as np
import matplotlib.pyplot as plt
import timeit
from functools import partial
from time import sleep
def list_comprehension(expensive_func):
return [
expensive_func(x)
for x in [1]
if expensive_func(x)
]
@optimize_comprehensions
def list_comprehension__optimized(expensive_func):
return [
expensive_func(x)
for x in [1]
if expensive_func(x)
]
func_times = [x / 100.0 for x in range(0, 50, 1)]
opt_comp_time_frac = []
for func_time in func_times:
print(func_time)
def expensive_func(x):
sleep(func_time)
return x
comp_time = timeit.timeit(
partial(list_comprehension, expensive_func),
number=10,
)
optimized_comp_time = timeit.timeit(
partial(list_comprehension__optimized, expensive_func),
number=10,
)
opt_comp_time_frac.append(optimized_comp_time / comp_time)
with plt.rc_context({'axes.edgecolor':'gray', 'xtick.color':'gray', 'ytick.color':'gray', 'figure.facecolor':'white'}):
plt.plot(func_times, opt_comp_time_frac)
plt.ylabel('Execution time of optimized comp / original comp', fontsize=10, wrap=True)
plt.xlabel('Execution time of function (seconds)', fontsize=10)
plt.savefig('comprehension_optimization_analysis.svg')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment