[python-uk] A stack with better performance than using a list
Alex Willmer
alex at moreati.org.uk
Wed Jun 7 14:30:08 EDT 2017
On 7 June 2017 at 18:50, Jonathan Hartley <tartley at tartley.com> wrote:
> Ah. In writing this out, I have begun to suspect that my slicing of 'tokens'
> to produce 'args' in the dispatch is needlessly wasting time. Not much, but
> some.
To put some numbers out there, eliminating the slice is not always a
win. On Python 2.7.13 Jonathon's dispatch() is marginally faster for
len(line.split()) == 10. The break even is around 40. At 1000 and
above dispatch_1() is approx 25% faster. Same code on Python 3.6.1 was
approx the same speed (within 10%).
class Bench:
def foo(self): pass
def dispatch(self, line):
tokens = line.split()
method = getattr(self, tokens[0])
args = tokens[1:]
#method(*args)
def dispatch_1(self, line):
op, rest = line.split(None, 1)
method = getattr(self, op)
args = rest.split()
#method(*args)
python --version
Python 2.7.13
python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ ' x'*10"
"b.dispatch(s)"
1000000 loops, best of 3: 0.577 usec per loop
python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ ' x'*10"
"b.dispatch_1(s)"
1000000 loops, best of 3: 0.673 usec per loop
python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ ' x'*1000"
"b.dispatch(s)"
100000 loops, best of 3: 19.1 usec per loop
python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ ' x'*1000"
"b.dispatch_1(s)"
100000 loops, best of 3: 14.8 usec per loop
python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ '
x'*1000000" "b.dispatch(s)"
100 loops, best of 3: 16.9 msec per loop
python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ '
x'*1000000" "b.dispatch_1(s)"
100 loops, best of 3: 12.4 msec per loop
--
Alex Willmer <alex at moreati.org.uk>
More information about the python-uk
mailing list