Pythonic way to iterate through multidimensional space?

Gayathri J usethisid2014 at gmail.com
Wed Aug 6 01:34:13 EDT 2014


Dear Peter

Below is the code I tried to check if itertools.product() was faster than
normal nested loops...

they arent! arent they supposed to be...or am i making a mistake? any idea?


*############################################################*

*# -*- coding: utf-8 -*-*
*import numpy as np*
*import time*
*from itertools import product,repeat*
*def main():*
*    # N - size of grid*
*    # nvel - number of velocities*
*    # times - number of times to run the functions*
*    N=256*
*    times=3*
*    f=np.random.rand(N,N,N)*

*    # using loops*
*    print "normal nested loop"*
*    python_dot_loop1(f,times,N)*

*    print "nested loop using itertools.product()"*
*    python_dot_loop2(f,times,N)*

*def python_dot_loop1(f,times,N):*
*    for t in range(times):*
*         t1=time.time()*
*         for i in range(N):*
*             for j in range(N):*
*                   for k in range(N):*
*                       f[i,j,k] = 0.0*
*         print "python dot loop " + str(time.time()-t1)*

*def python_dot_loop2(f,times,N):*
*    rangeN=range(N)*
*    for t in range(times):*
*         t1=time.time()*
*         for i,j,k in product(rangeN,repeat=3):*
*             f[i,j,k]=0.0*
*         print "python dot loop " + str(time.time()-t1)*


*if __name__=='__main__':*
*    main()*
*############################################################*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140806/28edef59/attachment.html>


More information about the Python-list mailing list