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

后端 未结 3 440
深忆病人
深忆病人 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条回答
  •  旧时难觅i
    2020-12-09 17:27

    You can also trick python:

    expression = "math.sin(v['x']) * v['y']"
    exp_as_func = eval('lambda: ' + expression)
    

    And then use it like so:

    exp_as_func()
    

    Speed test:

    In [17]: %timeit eval(expression)
    10000 loops, best of 3: 25.8 us per loop
    
    In [18]: %timeit exp_as_func()
    1000000 loops, best of 3: 541 ns per loop
    

    As a side note, if v is not a global, you can create the lambda like this:

    exp_as_func = eval('lambda v: ' + expression)
    

    and call it:

    exp_as_func(my_v)
    

提交回复
热议问题