module ns access vs. local access vs. builtin methods

Roman Suzi rnd at onego.ru
Mon Jul 16 03:24:45 EDT 2001


I've got interesting profile results which show that
using string methods is faster than other optimisation tricks:

--- aaaa.py ---
import profile, string

def a1(s):
  for k in xrange(200):
    K = 0
    for l in string.split(s):
      K = K+1

def a2(s, ssplit=string.split):
  for k in xrange(200):
    K = 0
    for l in ssplit(s):
      K = K+1

def a3(s):
  for k in xrange(200):
    K = 0
    for l in s.split():
      K = K+1

def runner(x, y):
  for c in xrange(25):
    x(y)

profile.run("""
runner(a1,"aaa "*50)
""")

profile.run("""
runner(a2,"aaa "*50)
""")

profile.run("""
runner(a3,"aaa "*50)
""")


----------------------------------------

$ python2.1 aaaa.py > aaaa.res

--- aaaa.res ---

         5028 function calls in 2.690 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.620    2.620 <string>:2(?)
        1    0.000    0.000    2.620    2.620 aaaa.py:21(runner)
       25    1.150    0.046    2.620    0.105 aaaa.py:3(a1)
        1    0.070    0.070    2.690    2.690 profile:0(
runner(a1,"aaa "*50)
)
        0    0.000             0.000          profile:0(profiler)
     5000    1.470    0.000    1.470    0.000 string.py:103(split)


         5028 function calls in 2.690 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.690    2.690 <string>:2(?)
        1    0.000    0.000    2.690    2.690 aaaa.py:21(runner)
       25    1.190    0.048    2.690    0.108 aaaa.py:9(a2)
        1    0.000    0.000    2.690    2.690 profile:0(
runner(a2,"aaa "*50)
)
        0    0.000             0.000          profile:0(profiler)
     5000    1.500    0.000    1.500    0.000 string.py:103(split)


         28 function calls in 1.960 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.940    1.940 <string>:2(?)
       25    1.940    0.078    1.940    0.078 aaaa.py:15(a3)
        1    0.000    0.000    1.940    1.940 aaaa.py:21(runner)
        1    0.020    0.020    1.960    1.960 profile:0(
runner(a3,"aaa "*50)
)
        0    0.000             0.000          profile:0(profiler)

-------------------------

a3 is clear winner, which probably mean that calling
methods of built-in types is faster than calling
functions.

And the trick with localising functions doesn't work
(or maybe I did it wrong).


Sincerely yours, Roman Suzi
-- 
_/ Russia _/ Karelia _/ Petrozavodsk _/ rnd at onego.ru _/
_/ Monday, July 16, 2001 _/ Powered by Linux RedHat 6.2 _/
_/ "Every man's work is a portrait of himself." _/





More information about the Python-list mailing list