简体   繁体   English

我可以使用eval重新创建代码,它会提高性能吗?

[英]Can I recreate the code using eval, will it improve performance?

I have an infinite loop using while true in this loop end, I always check if this is the first iteration of the loop if this is the first iteration continue, if this is the second and on sleep(1200) 我有一个无限循环,在循环结束时使用while true,我总是检查这是否是循环的第一次迭代,如果这是第一次迭代继续,如果这是第二次并在sleep(1200)

I wonder what is the best way to avoid checking each iteration the if condition? 我想知道避免检查每次迭代if条件的最佳方法是什么? that condition is true only once and I will run the loop for 10^10000 times. 该条件仅适用一次,因此我将循环运行10 ^ 10000次。

Is there a performance benefit from using eval as so: 像这样使用eval是否有性能优势:

crazy = r""" crazy = "sleep(120)" """

while True:
    // do some code
    eval(crazy)

This will rewrite crazy var at first loop, later will execute the sleep only. 这将在第一次循环时重写crazy var,稍后将仅执行睡眠。 I know it is unsafe, but one day smart code will be a code that write it self. 我知道这是不安全的,但是有一天,智能代码将是一种自我编写的代码。

I doubt eval is going to be any more efficient than if . 我怀疑eval会比if更有效率。

If you want to avoid an 'if' then the following code will work. 如果要避免使用“ if”,则以下代码将起作用。

n=0
while True:
    // do some code
    sleep(n)
    n=1200

Or to remove that line entirely 或者完全删除该行

doSomeCode()
while True:
    doSomeCode()
    sleep(1200)

But to be honest, unless you know you have a specific performance problem, that's not masked by the fact you're looping only once every 20 minute, you're probably optimising prematurely. 但老实说,除非您知道存在特定的性能问题,否则您不会每隔20分钟循环一次,这可能不会掩盖您可能过早地进行了优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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