Check out the Pastebin Gadgets Shop. We have thousands of fun, geeky & affordable gadgets on sale :-)Want more features on Pastebin? Sign Up, it's FREE!
tweet

# 2D fromiter example

By: a guest on Jan 17th, 2011  |  syntax: Python  |  size: 1.29 KB  |  views: 125  |  expires: Never
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
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'
clone this paste RAW Paste Data
Top