在我的代码中,我eval
用来评估用户给出的字符串表达式。有没有办法编译或以其他方式加速这个语句?
import math
import random
result_count = 100000
expression = "math.sin(v['x']) * v['y']"
variable = dict()
variable['x'] = [random.random() for _ in xrange(result_count)]
variable['y'] = [random.random() for _ in xrange(result_count)]
# optimize anything below this line
result = [0] * result_count
print 'Evaluating %d instances of the given expression:' % result_count
print expression
v = dict()
for index in xrange(result_count):
for name in variable.keys():
v[name] = variable[name][index]
result[index] = eval(expression) # <-- option ONE
#result[index] = math.sin(v['x']) * v['y'] # <-- option TWO
为了快速比较,选项 ONE 在我的机器上需要 2.019 秒,而选项 2 只需要 0.218 秒。当然,Python 有一种方法可以做到这一点,而无需对表达式进行硬编码。