SHARE
TWEET

2D fromiter example

a guest Jan 17th, 2011 143 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import numpy as np                                    
  2. import itertools as it                                
  3. import timeit                                        
  4.  
  5. def use_list(c):
  6.     return np.array(list(c), dtype=np.complex64)
  7.  
  8. def use_tuple(c):
  9.     return np.array(tuple(c), dtype=np.complex64)
  10.  
  11. def use_fromiter(x, length, c):
  12.     count = len(x) ** length
  13.     base_dtype = '<c8' # 64bit (i.e. 32bit native) complex
  14.     dtype = ','.join(length*[base_dtype])
  15.  
  16.     data = np.fromiter(c, dtype=dtype, count=count)
  17.     data = data.view(base_dtype).reshape((-1, length))
  18.  
  19.     return data
  20.  
  21. length = 9
  22. x = [1,-1,np.complex(0,1), np.complex(0,-1)]
  23.  
  24. if __name__ == '__main__':
  25.     t1 = timeit.timeit('use_fromiter(x, length, it.product(x, repeat=length))',
  26.             setup='from __main__ import use_fromiter, length, x, it', number=1)
  27.     t2 = timeit.timeit('use_list(it.product(x, repeat=length))',
  28.             setup='from __main__ import use_list, length, x, it', number=1)
  29.     t3 = timeit.timeit('use_tuple(it.product(x, repeat=length))',
  30.             setup='from __main__ import use_tuple, length, x, it', number=1)
  31.  
  32.     print 'Times using a repeat of', length, ':'
  33.     print 'Time using np.fromiter', t1, 's'
  34.     print 'Time using lists', t2, 's'
  35.     print 'Time using tuples', t3, 's'
RAW Paste Data
Want to get better at Python?
Learn to code Python in 2017
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top