Python saving an eval function

北城以北 提交于 2019-12-10 13:13:26

问题


Say I have a function fun(f, x, y) where x and y are numbers and f is a string specifying a function such as "1 / x ** 2 + y".

I wish to use this function f a lot, say a few million times, and the values of x and y change between each use.
Therefore calling eval(f) takes a significant amount of time as opposed to just calculating the value of the function each time. (About 50x, in my measured case.)

Is there any way to save this function f so that I would only have to call eval once?

PS. Please do not discuss the (un)safety of using eval here, I am aware of it, but this code isn't going anywhere where a 3rd party will run it, nor is it relevant to my question.


回答1:


You could eval the lambda, so you just evaluate it once, and after that it's a function that you can use:

s = "1 / x ** 2 + y"

s = "lambda x,y: "+s
f = eval(s)
x = 2
y = 3
print(f(x,y))

I get 3.25, but I can change x and y as many times I need without evaluating the expression again.




回答2:


If Jean_Francois' solution still isn't fast enough, you can take a look at numba. f_numba = jit(f), and then probably also @jit the function that calls f_numba so that f_numba is inlined into the caller. Depends on your application.



来源:https://stackoverflow.com/questions/43777551/python-saving-an-eval-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!