I'm writing a program that has to execute Python code from a string millions of times. Is there a faster way to do this than using eval()
? Running the code in eval()
takes about 100 microseconds, and running it embedded in the program only takes 8 microseconds. Is there a method similar to eval()
that takes less time to execute?
I would restructure your code so that it doesn't have to be eval
ed (e.g., take a function argument instead of a string)
If the equation absolutely must come from a string, you could compile it beforehand:
In [1]: x = y = 0
In [2]: %timeit eval('x ** 2 + y')
5.95 µs ± 223 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [3]: code = compile('x ** 2 + y', '<string>', 'eval')
In [4]: %timeit eval(code)
608 ns ± 9.88 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Rather than having eval
compile the string to bytecode every time it is called, compile
does that beforehand.