Python: Way to speed up a repeatedly executed eval statement?

后端 未结 3 438
深忆病人
深忆病人 2020-12-09 16:47

In my code, I\'m using eval to evaluate a string expression given by the user. Is there a way to compile or otherwise speed up this statement?

         


        
3条回答
  •  悲&欢浪女
    2020-12-09 17:18

    You can avoid the overhead by compiling the expression in advance using compiler.compile() for Python 2 or compile() for Python 3 :

    In [1]: import math, compiler
    
    In [2]: v = {'x': 2, 'y': 4}
    
    In [3]: expression = "math.sin(v['x']) * v['y']"
    
    In [4]: %timeit eval(expression)
    10000 loops, best of 3: 19.5 us per loop
    
    In [5]: compiled = compiler.compile(expression, '', 'eval')
    
    In [6]: %timeit eval(compiled)
    1000000 loops, best of 3: 823 ns per loop
    

    Just make sure you do the compiling only once (outside of the loop). As mentioned in comments, when using eval on user submitted strings make sure you are very careful about what you accept.

提交回复
热议问题