How can I optimise this? [intended in good humour]

Paul McGuire ptmcg at austin.rr._bogus_.com
Mon Jul 24 11:47:20 EDT 2006


"John Machin" <sjmachin at lexicon.net> wrote in message
news:1153733237.943779.58670 at h48g2000cwc.googlegroups.com...
> Markus wrote:
> > You know you're guilty of early/over optimisation, when it's almost two
> > in the morning and the file open in front of you reads as follows.
> >
<snip>
> >
> > from timeit import Timer
> >
> > if __name__=='__main__':
> >      t = Timer('len(argv)==1','from sys import argv')
> >      print "%f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
> >      t = Timer('argv[0]==argv[-1]','from sys import argv')
> >      print "%f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
> >
> > [-snip-]

You're worried about the performance of len(sys.argv)?! Is your command line
processing *really* your program bottleneck?  If so, I'd say making a better
len is the least of your problems.

Hard to imagine you'll do better than len, especially for lists as short as
command line args.  If you are *really* doing lots of len'ning, copy len to
a local to cut down on lookup costs:

C:\Documents and Settings\Paul>python -mtimeit -s"a=['abc','abc']" "len(a)"
1000000 loops, best of 3: 0.218 usec per loop

C:\Documents and Settings\Paul>python -mtimeit -s"a=['abc','abc'];len_=len"
"len_(a)"
10000000 loops, best of 3: 0.172 usec per loop

But honestly, do some profiling before adding these maintenance-hindering
and readability-impairing "optimizations."

-- Paul





More information about the Python-list mailing list