Skip to content

Instantly share code, notes, and snippets.

@DanHickstein
Created September 5, 2018 13:16
Show Gist options
  • Save DanHickstein/0a0ca523c22f9ad02fe786bfc2d842a9 to your computer and use it in GitHub Desktop.
Save DanHickstein/0a0ca523c22f9ad02fe786bfc2d842a9 to your computer and use it in GitHub Desktop.
Comparison of np.linalg.solve
import numpy as np
import matplotlib.pyplot as plt
import timeit
import time
length = 10
ns = 2**np.arange(0,length)
t0s = np.zeros(length)
t1s = np.zeros(length)
fig, axs = plt.subplots(2,1, figsize=(6,7), tight_layout=True)
for count, n in enumerate(ns):
setup = '''import numpy as np; A = np.random.random((%i,%i)); b = np.random.random((%i,%i))'''%(n,n,n,n)
t0s[count] = timeit.timeit('Ai = np.linalg.inv(A); x0 = np.dot(Ai, b)', setup=setup, number=3)
t1s[count] = timeit.timeit('x1 = np.linalg.solve(A, b)' , setup=setup, number=3)
axs[0].plot(ns, t0s, 'ro', label='inv and dot')
axs[0].plot(ns, t1s, 'bo', label='np.linalg.solve')
axs[0].legend()
axs[0].set_yscale('log')
axs[0].set_xscale('log')
axs[0].set_ylabel('Time (sec)')
axs[0].set_xlabel('Square matrix width/height (n)')
axs[1].plot(ns, t1s/t0s, 'mo', label='Ratio of np.linalg.solve / inv and dot')
axs[1].set_xscale('log')
axs[1].set_ylabel('Ratio')
axs[1].set_xlabel('Square matrix width/height (n)')
axs[1].set_ylim(0,2)
axs[1].axhline(np.mean(t1s/t0s), color='m', lw=1, ls='dotted', label='mean: %.2f'%(np.mean(t1s/t0s)))
axs[1].axhline(1, color='k', lw=1, ls='dashed', alpha=0.5)
axs[1].legend(loc='lower right')
for ax in axs:
ax.grid(color='k', alpha=0.05)
plt.savefig('Comparison of linalg.png', dpi=250)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment