Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Python: Общие вопросы > a.f() или f(a) ?


Автор: setq 26.5.2006, 18:21
Предположим есть такой код

Код

>>> class A:
...    def f(self):
...        ...do something...
...
>>> f = A.f
>>> a = A()
>>>


Какой вызов будет быстрее: a.f() или f(a)? 

Автор: J2A 26.5.2006, 19:52
Проверь. В чем проблема?


Код

Python 2.3.5 (#2, Nov 20 2005, 16:40:39) 
[GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import hotshot
>>> import hotshot.stats
>>> class A:
...     def f(self):
...         hash(self)
... 
>>> def example1():
...     a = A()
...     for i in xrange(1000000):
...         a.f()
... 
>>> def example2():
...     a = A()
...     f = A.f
...     for i in xrange(1000000):
...         f(a)
... 
>>> prof1 = hotshot.Profile('ex1.prof')
>>> prof1.runcall(example1)
>>> prof2 = hotshot.Profile('ex2.prof')
>>> prof2.runcall(example2)
>>> stats1 = hotshot.stats.load('ex1.prof')
>>> stats1.sort_stats('time', 'calls')
<pstats.Stats instance at 0xb7d7166c>
>>> stats1.print_stats(5)
         1000001 function calls in 24.209 CPU seconds

   Ordered by: internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000   17.007    0.000   17.007    0.000 <stdin>:2(f)
        1    7.202    7.202   24.209   24.209 <stdin>:1(example1)
        0    0.000             0.000          profile:0(profiler)


<pstats.Stats instance at 0xb7d7166c>
>>> stats2 = hotshot.stats.load('ex2.prof')
>>> stats2.sort_stats('time', 'calls')
<pstats.Stats instance at 0xb7d71bcc>
>>> stats2.print_stats(5)
         1000001 function calls in 24.414 CPU seconds

   Ordered by: internal time, call count

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  1000000   15.984    0.000   15.984    0.000 <stdin>:2(f)
        1    8.430    8.430   24.414   24.414 <stdin>:1(example2)
        0    0.000             0.000          profile:0(profiler)


<pstats.Stats instance at 0xb7d71bcc>
  

Автор: setq 27.5.2006, 15:46
Спасибо. 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)