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?
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
For a quick comparison option ONE takes 2.019 seconds on my machine, while option TWO takes only 0.218 seconds. Surely Python has a way of doing this without hard-coding the expression.
You can also trick python:
And then use it like so:
Speed test:
As a side note, if
v
is not a global, you can create the lambda like this:and call it:
You can avoid the overhead by compiling the expression in advance using
compiler.compile()
: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.I think you are optimising the wrong end. If you want to perform the same operation for a lot of numbers you should consider using numpy:
To give you an idea about the possible gain I've added a variant using generic python and the lambda trick:
Here are the results on my aging machine:
The speed-up is not as high as I expected, but still significant.