简体   繁体   中英

How do I evaluate Python code from a string quickly?

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 (eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM