如何使迭代更快?

2024-09-24 02:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个循环:

for i in range(self.worldWidth):
    for j in range(self.worldHeight):
        originalValue = self.world.world[i, j]
        # Process newValue
        self.world.world[i, j] = newValue
        

当世界大小为(500500)时,它的运行速度约为每秒10次,这对于我正在做的事情来说很慢,当我尝试用C#做同样的事情时,我得到了三倍的速度(每秒30次)。
有什么办法可以加快速度吗

注意:这些速度的计算不需要对该值进行任何处理

编辑:在使用C#进行进一步测试后,我得到了大约10倍的速度(只是第一次速度很慢),但在python中,每次大约0.07秒


Tags: inselfforworld世界range事情process
2条回答

可能通过使用range关键字将self.worldWidthself.worldHeight声明为带有插入数字的列表。 这将保存每次迭代的下一个()数的计算

注意-与使用循环中下一个索引计算的范围选项相比,这种方法将导致内存浪费

不知道你想做什么,但把numpy标记作为一个指标。Numpy在编译代码中运行其内部循环,因此比使用显式Python循环快得多

import numpy as np

world = np.zeros( ( 500, 500 ) )

world[:] = 42

def test( world, v ):
    for r, row in enumerate( world ):
        for c, col in enumerate( row ):
            world[ r, c ] = v 

test( world, 42 )

%timeit world[:] = 42                                                   
# %timeit 110 µs ± 1.58 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit test( world, 43 )                                               
# 69.9 ms ± 1.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

如果您需要计算,如果可以在numpy中定义,这些计算也可以快得多

weight = np.arange( 500 )/250

def test_loop( world, weight ):
    w = world.copy()
    for r, row in enumerate( world ):
        for c, col in enumerate( row ):
            w[ r, c ] *= weight[c]
    return w

test_loop( world, weight )

def test_np( world, weight ):
    w = world.copy()
    return world * weight

np.isclose( test_loop( world, weight ),test_np( world, weight )).all()
# True  # The two results are equivalent.

%timeit test_np( world, weight )                                        
# 754 µs ± 1.71 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit test_loop( world, weight )                                      
# 172 ms ± 3.62 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

正如一些评论所暗示的那样。这取决于生成newValue所需的计算。考虑到计算时间的潜在改进,可能值得为您的应用程序探索numpy

相关问题 更多 >