简体   繁体   English

在 Python 中检查模数的更快方法

[英]Faster way to check moduli in Python

I've been writing simulation codes for a while, and there's always a main loop that looks like this, in this case in Python:我已经写了一段时间的模拟代码,并且总是有一个看起来像这样的主循环,在本例中为 Python:

while t<totalTimesteps:
    
    t += 1
    processOneTimestep()

    outputData()

the line outputData() writes results to a file one per timestep for analysis.outputData()每个时间步将结果写入一个文件以进行分析。 This writing can take quite a bit of time, and we usually don't need the state of whatever we are doing in every single timestep, so it will usually look like this:这篇文章可能需要相当长的时间,而且我们通常不需要我们在每个时间步中所做的任何事情的 state,所以它通常看起来像这样:

while t<totalTimesteps:
    
    t += 1
    processOneTimestep()

    if t%N == 0:
        outputData()

where N is an integer that sets how often we write.其中N是一个 integer,它设置我们写的频率。 Assuming the simulation and writing themselves are very optimized, is there a way in Python to accelerate that modulus check, or to use inline Python magic to make it faster?假设模拟和编写本身非常优化,Python 中是否有办法加速模数检查,或者使用内联 Python 魔法使其更快? Is that if line as fast as it can be in Python? if线路尽可能快地在 Python 中?

I don't know if it's faster, but you could use nested loops.我不知道它是否更快,但你可以使用嵌套循环。

for tsteps in range(0, totalTimesteps, N):
    for t in range(tsteps, min(tsteps+N, totalTimesteps)):
        processOneTimestep()
    outputData()

You could use map to apply a function to all index.您可以使用 map 将 function 应用于所有索引。 To get all the different index you could use range, and you could use a lambda function to get a more concise code.要获得所有不同的索引,您可以使用范围,您可以使用 lambda function 来获得更简洁的代码。

N=3 #example N

map(
    lambda i: (processOneTimestep(), outputData()) if i%N==0 else processOneTimestep(),
    range(totalTimesteps)
)

This code would execute both functions when i%N==0 in other case will only execute processOneTimestep()此代码将在i%N==0时执行这两个函数,在其他情况下只会执行processOneTimestep()

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

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