[Python-ideas] Interrogate alternate namespace keyword and concept

ilya ilya.nikokoshev at gmail.com
Fri Aug 14 22:29:11 CEST 2009


That's a useful statistics, but the bottleneck is **only** because of
parsing 'value +=5'.

Here's how I time it:

# insert my old program here...


from timeit import Timer
from codeop import compile_command

def timing(something):
    setup = 'from __main__ import test, interrogate, command, inc5'
    best = sorted(Timer(something, setup).repeat(3, 1000))[0]
    print('{0!r} -> {1:.3} ms'.format(something, best))
    print('# test.value =', test.value)

command = '''
for i in range(10):
    value += 1
'''

inc5 = compile_command(command)

timing("interrogate(test, command)")
timing(command.replace('value', 'test.value'))
timing("interrogate(test, inc5)")

Result:

15
'interrogate(test, command)' -> 0.0908 ms
# test.value = 30015
'\nfor i in range(10):\n    test.value += 1\n' -> 0.00408 ms
# test.value = 60015
'interrogate(test, inc5)' -> 0.00469 ms
# test.value = 90015

so interrogate() with additional precompiling introduces very little
overhead. Though I agree it's inconvenient to write functions as
strings; I think someone smarter than me can find a way to do it like
a regular function call.



On Fri, Aug 14, 2009 at 3:17 PM, Steven D'Aprano<steve at pearwood.info> wrote:
> On Fri, 14 Aug 2009 07:35:55 pm ilya wrote:
>> Sorry, it's actually even easier; interrogate() is a one-liner:
>>
>> class Test:
>>    '''Class to be interrogated.'''
>>    def __init__(self, value):
>>        self.value = value
>>
>> test = Test(10)
>>
>> def interrogate(what, how):
>>    exec(how, what.__dict__)
>
> Apart from the security implications of exec(), it also takes a fairly
> hefty performance hit. In Python 2.6:
>
>>>> from timeit import Timer
>>>> setup = 'from __main__ import test, interrogate'
>>>> Timer("interrogate(test, 'value += 5')", setup).repeat()
> [18.503479957580566, 18.218451023101807, 18.218581914901733]
>>>> Timer("test.value += 5", setup).repeat()
> [0.33056807518005371, 0.33118104934692383, 0.33114814758300781]
>
> That's a factor of 55 times slower -- not precisely an optimization.
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



More information about the Python-ideas mailing list