python - Why Numpy.array is slower than build-in list for fetching sub list -


i'm going improve performance of code snippet getting sub-array recursively.

so used numpy.array instead of build-in list. because, know, when fetching sub-array, numpy.array don't copy orginal list.

but when changed numpy.array, performance got worse. want know reason. thanks!

following code snippet , execution times using different objects got:

import timeit stat = '''  import numpy def func(a):     a[len(a)-1] += 1     if len(a) == 1:         return a[0]     else:         return func(a[1:len(a)]) a1=[1,2,3,4,5,6,7,8,9,10] a2=numpy.array([1,2,3,4,5,6,7,8,9,10]) ''' if __name__ == "__main__":     print "execution time build-in list: {0}".format(timeit.timeit('func(a1)', setup = stat, number = 1000))     print "execution time numpy array: {0}".format(timeit.timeit('func(a2)', setup = stat, number = 1000)) 

and on 64-bit mac(python 2.7.6 + numpy 1.8.0rc1) output is:

execution time build-in list: 0.00507998466492 execution time numpy array: 0.0195469856262 

you same execution times if modify 2 last lines of code follows:

print "execution time build-in list: {0}".format(timeit.timeit(     'func(a1)', setup = stat, number = 1000), 'gc.enable()') print "execution time numpy array:   {0}".format(timeit.timeit(     'func(a2)', setup = stat, number = 1000), 'gc.enable()') 

where in both cases allowed timeit switch on so-called garbage collection, i.e. process of freeing memory when not used anymore. abovementioned modification returns, e.g.:

execution time build-in list: 0.00580596923828 execution time numpy array:   0.00822710990906 

to of same order of magnitude. according documentation of timeit "by default, temporarily turns off garbage collection during timing. advantage of approach makes independent timings more comparable. disadvantage garbage collection may important component of performance of function being measured."

there thin understanding method, i.e. or without garbage collection, should used , when. please note, obtain longer times if apply time.time() block time module.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -