[FRPythoneers] performance of cmp()

Bob Gailer bgailer at alum.rpi.edu
Tue Sep 23 07:39:56 MDT 2003


At 02:53 AM 9/23/2003, you wrote:

>I just finished writing my first python program. I have a performance
>critical loop in which 2 strings are compared. My initial code looked
>like this:
>
>if a < b:
>   ...
>elsif a > b:
>   ...
>else:
>   ...
>
>Knowing that 2 string comparisons are inefficient

Actually one does not "know"; one assumes, then does performance/timing 
tests as you have done.

>I found the cmp()
>method and did:
>
>i = cmp(a,b)
>if i > 0:
>   ...
>elsif i < 0:
>   ...
>else:
>   ---
>
>To my surprise the second version kept performing *slower* than the
>first. Why this (unexpected) behavior?

You are trading  2 string compares for a function call and 2 integer 
compares. Timing tests are useful here:

 >>> import time
 >>> def f(strlen, cycles=10000):
...     s = time.time();str1 = 'a'*strlen+'b';str2 = 'a'*strlen+'c'
...     for i in range(cycles):
...             x = cmp(str1, str2)
...             if x > 0:pass
...             elif x < 0:pass
...     s2 = time.time();print s2 - s
...     for i in range(cycles):
...             if str1 > str2:pass
...             elif str1 < str2:pass
...     print time.time() - s2
...
 >>> f(1000, 100000)
0.771000027657
0.710999965668

Vary the string length and notice how long the strings have to be before 
cmp is more effective!

Also step back and ask whether there's another way to accomplish your goal.

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003


More information about the FRPythoneers mailing list