Wednesday, 7 October 2020

improve performance of list creation

How can I improve significantly the speed of the following code? Can mapping, numpy, matrix operations be efficiently used and/or something else to omit the for loop?

import time

def func(x):
    if x%2 == 0:
        return 'even'
    else:
        return 'odd'

starttime = time.time()

MAX=1000000

y=list(range(MAX))

for n in range(MAX):
    y[n]=[n,n**2,func(n)]

print('That took {} seconds'.format(time.time() - starttime))

The following replacement does not improve the speed:

import numpy as np
r = np.array(range(MAX))
str = ['odd', 'even']
result = np.array([r, r ** 2, list(map(lambda x: str[x % 2], r))])
y = result.T


from improve performance of list creation

No comments:

Post a Comment