orderedset is a C extension for Python, an implementation in Cython, based on a pure Python implementation, as its name has suggested it’s a library for ordered sets. For quick example to understand what it does and good comparison with the standard set:
the_set = (1, 2, 4, 3) from orderedset import OrderedSet print(OrderedSet(the_set)) print(set(the_set))
This results in Python 2:
OrderedSet([1, 2, 4, 3]) set([1, 2, 3, 4])
In Python 3, the representation of set is {1, 2, 3, 4}.
It clearly shows the order is kept within the set. I wrapped out a quick benchmarking code using timeit:
#!/usr/bin/env python from timeit import timeit t = timeit( 'OrderedSet(the_set)', setup=('from orderedset import OrderedSet;' 'the_set = (1, 2, 4, 3)'), number=1000000) print(t) t = timeit('set(the_set)', setup='the_set = (1, 2, 4, 3)', number=1000000) print(t) # http://code.activestate.com/recipes/576694/ # Save recipe-576694-1.py as OrderedSet.py t = timeit( 'OrderedSet(the_set)', setup=('from OrderedSet import OrderedSet;' 'the_set = (1, 2, 4, 3)'), number=1000000) print(t)
Here is the results for the execution time, 1,000,000 executions, in seconds:
Python Version | set | Cython | Python |
---|---|---|---|
Python 2.7.5 | 0.502 | 2.124 | 8.706 |
Python 3.3.3 | 0.503 | 2.234 | 8.559 |
Note
set is included for comparison for execution time only.
Between Python 2 and 3, there really is no much different in the implementations. They are all quite close across the Python versions. Between the implementations, set is the fastest, however, since order is the whole point, even it’s more than 4 times faster, it doesn’t matter because order information is not kept. This Cython implementation is 4 times faster than the pure Python’s, clearly is the winner.
orderedset is written in Cython by Simon Percivall based on Raymond Hettinger’s pure Python OrderedSet implementation, under the New BSD License (3-clause), currently version 1.0.2 (2014-05-13), compilable for both Python 2 and 3.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.