Skip to content

Instantly share code, notes, and snippets.

@lclarkmichalek
Created February 18, 2014 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lclarkmichalek/9080540 to your computer and use it in GitHub Desktop.
Save lclarkmichalek/9080540 to your computer and use it in GitHub Desktop.
import numpy as np
import timeit
def random_data(N):
return np.random.uniform(0., 10., N)
array1 = np.array([random_data(4) for _ in range(1000)])
array2 = np.array([random_data(4) for _ in range(2000)])
def func():
lst = []
for elem in array1:
# Define factors.
a_01, a_11 = max(elem[1], 1e-10), max(elem[3], 1e-10)
a_02, a_12 = array2[:,1], array2[:,3]
# Combine the factors defined above.
a_0 = a_01**2 + a_02**2
a_1 = a_11**2 + a_12**2
Bs, Cs = -0.5/a_0, -0.5/a_1
# Perform operations.
A = 1./(np.sqrt(a_0*a_1))
B = Bs*(elem[0]-array2[:,0])**2
C = Cs*(elem[2]-array2[:,2])**2
ABC = A*np.exp(B+C)
lst.append(max(ABC.sum(), 1e-10))
return lst
def func2():
lst = []
# Define factors.
a_02, a_12 = array2[:,1], array2[:,3]
a_022 = a_02 ** 2
a_122 = a_12 ** 2
e10 = np.array([1e-10 for _ in xrange(len(array1))])
a_01 = np.maximum(array1[:,1], e10)
a_11 = np.maximum(array1[:,3], e10)
for i, elem in enumerate(array1):
# Combine the factors defined above.
a_0 = a_01[i]**2 + a_022
a_1 = a_11[i]**2 + a_122
Bs, Cs = -0.5/a_0, -0.5/a_1
# Perform operations.
A = 1./(np.sqrt(a_0*a_1))
B = Cs*(elem[0]-array2[:,0])**2
C = Cs*(elem[2]-array2[:,2])**2
ABC = A*np.exp(B+C)
lst.append(max(ABC.sum(), 1e-10))
return lst
N = 100
func_time = timeit.timeit(func, number=N)
print "Original\t", func_time / N
print "-" * 50
func2_time = timeit.timeit(func2, number=N)
print "Revision 1\t", func2_time / N
print "Improvement\t", str(int((func_time - func2_time) / func_time * 100)) + "%"
print "-" * 50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment