python - Difference of two tuples containing Long numbers -
i have 2 tuples of long
values. need difference of them, x2-x1
.
x1 = (2873120768, 2873122560, 2873123328) x2 = (2873121279, 2873122815, 2873123583)
expected result:
result = (511,255,255)
but not matter if tuple or list
i looking way not element element if possible. speed constraint. searched couldn't find answer.
thank in advance
in pure python fastest way utilize map
operator.sub
:
>>> operator import sub >>> map(sub, x2, x1) [511l, 255l, 255l] #if want tuple output >>> itertools import imap >>> tuple(imap(sub, x2, x1)) (511l, 255l, 255l)
if not plenty switch numpy:
>>> x1_arr = np.array(x1) >>> x2_arr = np.array(x2) >>> x2_arr - x1_arr array([511, 255, 255])
let's time them:
>>> x1 = (2873120768l, 2873122560l, 2873123328l)*10**5 >>> x2 = (2873121279l, 2873122815l, 2873123583l)*10**5 >>> %timeit map(sub, x2, x1) 100 loops, best of 3: 19.3 ms per loop >>> %timeit tuple(imap(sub, x2, x1)) 10 loops, best of 3: 19.9 ms per loop >>> %timeit [j - i,j in zip(x1, x2)] 10 loops, best of 3: 38.2 ms per loop
using iterools.izip
(python 2) or zip
in python 3 create list comprehension version fast map
:
>>> %timeit [j - i,j in izip(x1, x2)] 10 loops, best of 3: 20.5 ms per loop >>> %timeit tuple(i-j i,j in zip(x2,x1)) 10 loops, best of 3: 40.5 ms per loop >>> %timeit tuple(i-j i,j in izip(x2,x1)) 10 loops, best of 3: 25.1 ms per loop #numpy arrays >>> %timeit x2_arr - x1_arr 1000 loops, best of 3: 469 µs per loop
python performance tuples
No comments:
Post a Comment