[Tutor] What's the problem with my SpinSpeeds.py?

Alan Gauld alan.gauld at blueyonder.co.uk
Mon Aug 2 20:21:04 CEST 2004


> My thanks to dragonfirebane, Alan Gauld, and Kent Johnson for their
help
> and guidance.  I don't  really grasp yet what's going on, but here's
what
> I have now. It incorporates all of their suggestions.   --Dick

You only needed a subset of them they solve the same problem in
different
ways.:-)

>      t = Timer("countUsingRange(n)", "from __main__ import
> countUsingRange, n")
>      rangeTime = t.timeit(repetitions)

This executes and times the string

"countUsingRange(n)"

after first executing

"from __main__ import countUsingRange, n".

The import step brings 'n' into scope for the timer so that the
first string can be evaluated correctly.

>      cmd = "countUsingXrange(%d)" % n
>      t = Timer(cmd, "from __main__ import countUsingXrange")
>      xrangeTime = t.timeit(repetitions)

This creates a string "countUsingXrange(XXX)"  where XXX is
the value of n. Then it creates a timer to execute and time
that string after first executing

"from __main__ import countUsingXrange"

which simply makes your function visible.

>      t = Timer("countUsingCounter(%d)" % n, "from __main__ import
> countUsingCounter")
>      counterTime = t.timeit(repetitions)

And this does exactly the same except that it creates the
command string inline.

Any one of the three techniques should work OK.
There is a subtle difference between them inasmuch as
the first puts slightly more work into the timing module
since it has to perform the variable substitution whereas
forming the string before entering the timer could be
slightly faster during timing, but the difference is
negligible in this case. Preforming the string allows
multiple timers to be easily created for the same command
should you need to do so...

Alan G.



More information about the Tutor mailing list