timeit and SyntaxWarnings

Michele Simionato mis6 at pitt.edu
Tue May 27 15:38:30 EDT 2003


I was experimenting with the new timeit module and I have written the following
utility function:

  # timit.py script

  import timeit,__main__

  def timeit_(stmt,setup='from __main__ import *',n=1000000):
      t=timeit.Timer(stmt,setup)
      try: return t.repeat(number=n) # call timeit 3 times
      except: t.print_exc()

Now, I wanted to measure the function call overhead for functions with
no arguments and with optional arguments:

  def func_call1():
      pass

  def func_call2(*args,**kw):
      pass

  print 'func_call1:',timeit_('func_call1()')
  print 'func_call2:',timeit_('func_call2()')

It works:

$ p23 -W ignore timit.py
func_call1: [2.0951619148254395, 2.1110140085220337, 2.0941540002822876]
func_call2: [3.6085150241851807, 3.6067030429840088, 3.6114571094512939]

One can see that a function call with optional arguments is nearly twice 
more expensive than a function call without arguments (not really unexpected) 
and that Python 2.3 is much better than Python 2,2:

$ python2 -W ignore timit.py
func_call1: [3.0151200294494629, 3.0149120092391968, 3.0145740509033203]
func_call2: [6.0031960010528564, 6.0006380081176758, 6.0164029598236084]

However, if don't use the -W ignore option I get an annoying Syntax Warning:

$ p23 timit.py
<timeit-src>:2: SyntaxWarning: import * only allowed at module level
func_call1: [1.9198670387268066, 1.9196269512176514, 1.9194220304489136]
<timeit-src>:2: SyntaxWarning: import * only allowed at module level
func_call2: [3.4658629894256592, 3.4641860723495483, 3.4799900054931641]
<timeit-src>:2: SyntaxWarning: import * only allowed at module level

Of course, this is issued to discourage the "import *" form;
I know I could use as setup string 'import __main__' and then
write '__main__.func_call1' and '__main__.func_call2' as statements,
but I don't like this approach. During testing and in the interactive
section, I like very much the "from module import *" statement and I
would like to use it in timeit too. 

I guess the solution is to use the warnings module, however I never used it
and if somebody can provide an example I will be glad ;)

Moreover, I wonder if there is a better solution. In particular, is there 
any risk that in the future that SyntaxWarning will be converted to an error ?
 
Comments are very much appreciated ;)


                                                   Michele 


P.S. if somebody is interested, here are the results with the -O option
turned on:

$ p23 -O -W ignore timit.py
func_call1: [1.9523719549179077, 1.9523370265960693, 1.9526520967483521]
func_call2: [3.5159320831298828, 3.6002240180969238, 3.5969339609146118]

$ python2 -O -W ignore timit.py
func_call1: [2.6123529672622681, 2.6392279863357544, 2.6195629835128784]
func_call2: [5.5391669273376465, 5.5333319902420044, 5.5653229951858521]




More information about the Python-list mailing list