6

上下文:我的 Python 代码将二维顶点数组传递给 OpenGL。

我测试了 2 种方法,一种使用 ctypes,另一种使用 struct,后者快两倍以上。

from random import random
points = [(random(), random()) for _ in xrange(1000)]

from ctypes import c_float
def array_ctypes(points):
    n = len(points)
    return n, (c_float*(2*n))(*[u for point in points for u in point])

from struct import pack
def array_struct(points):
    n = len(points)
    return n, pack("f"*2*n, *[u for point in points for u in point])

还有其他选择吗?关于如何加速此类代码的任何提示(是的,这是我的代码的一个瓶颈)?

4

5 回答 5

3

您可以将 numpy 数组传递给 PyOpenGL,而不会产生任何开销。(datanumpy 数组的属性是一个缓冲区,指向底层 C 数据结构,其中包含与您正在构建的数组相同的信息)

import numpy as np  
def array_numpy(points):
    n = len(points)
    return n, np.array(points, dtype=np.float32)

在我的计算机上,这比struct基于 - 的方法快 40%。

于 2010-11-11T17:37:50.467 回答
2

你可以试试 Cython。对我来说,这给出了:

function       usec per loop:
               Python  Cython
array_ctypes   1370    1220
array_struct    384     249
array_numpy     336     339

因此,Numpy 仅在我的硬件(运行 WindowsXP 的旧笔记本电脑)上提供了 15% 的收益,而 Cython 提供了大约 35%(在您的分布式代码中没有任何额外的依赖)。

如果您可以放宽对每个点都是浮点数元组的要求,只需将“点”设置为扁平的浮点数列表:

def array_struct_flat(points):
    n = len(points)
    return pack(
        "f"*n,
        *[
            coord
            for coord in points
        ]
    )

points = [random() for _ in xrange(1000 * 2)]

那么结果输出是相同的,但时间会进一步下降:

function            usec per loop:
                    Python  Cython
array_struct_flat           157

如果比我更聪明的人想在代码中添加静态类型声明,Cython 也可能比这更好。(运行 'cython -a test.pyx' 对此非常宝贵,它会生成一个 html 文件,显示代码中最慢(黄色)纯 Python 的位置,而不是已转换为纯 C(白色)的 python。这就是为什么我将上面的代码展开到很多行,因为着色是每行完成的,所以它有助于像这样展开。)

完整的 Cython 说明在这里: http ://docs.cython.org/src/quickstart/build.html

Cython 可能会在整个代码库中产生类似的性能优势,并且在理想条件下,应用适当的静态类型,可以将速度提高十倍或一百倍。

于 2010-11-12T06:54:29.993 回答
1

我偶然发现了另一个想法。我现在没有时间对其进行分析,但万一其他人这样做:

 # untested, but I'm fairly confident it runs
 # using 'flattened points' list, i.e. a list of n*2 floats
 points = [random() for _ in xrange(1000 * 2)]
 c_array = c_float * len(points * 2)
 c_array[:] = points

也就是说,首先我们创建 ctypes 数组但不填充它。然后我们使用切片符号填充它。比我聪明的人告诉我,分配给这样的切片可能有助于提高性能。它允许我们直接在赋值的 RHS 上传递一个列表或迭代,而不必使用*iterable语法,这将执行一些可迭代的中间争吵。我怀疑这是在创建 pyglet 的批次的深处发生的事情。

大概你可以只创建一次 c_array ,然后每次点列表更改时重新分配给它(上面代码中的最后一行)。

可能有一个替代公式接受点的原始定义((x,y)元组的列表。)像这样:

 # very untested, likely contains errors
 # using a list of n tuples of two floats
 points = [(random(), random()) for _ in xrange(1000)]
 c_array = c_float * len(points * 2)
 c_array[:] = chain(p for p in points)
于 2010-11-23T15:48:22.173 回答
1

如果性能是一个问题,您不想使用带有星号操作的 ctypes 数组(例如,(ctypes.c_float * size)(*t))。

在我的测试pack中最快的是使用array带有地址转换的模块(或使用 from_buffer 函数)。

import timeit
repeat = 100
setup="from struct import pack; from random import random; import numpy;  from array import array; import ctypes; t = [random() for _ in range(2* 1000)];"
print(timeit.timeit(stmt="v = array('f',t); addr, count = v.buffer_info();x = ctypes.cast(addr,ctypes.POINTER(ctypes.c_float))",setup=setup,number=repeat))
print(timeit.timeit(stmt="v = array('f',t);a = (ctypes.c_float * len(v)).from_buffer(v)",setup=setup,number=repeat))
print(timeit.timeit(stmt='x = (ctypes.c_float * len(t))(*t)',setup=setup,number=repeat))
print(timeit.timeit(stmt="x = pack('f'*len(t), *t);",setup=setup,number=repeat))
print(timeit.timeit(stmt='x = (ctypes.c_float * len(t))(); x[:] = t',setup=setup,number=repeat))
print(timeit.timeit(stmt='x = numpy.array(t,numpy.float32).data',setup=setup,number=repeat))

在我的测试中,array.array 方法比 Jonathan Hartley 的方法略快,而 numpy 方法的速度大约只有一半:

python3 convert.py
0.004665990360081196
0.004661010578274727
0.026358536444604397
0.0028003649786114693
0.005843495950102806
0.009067213162779808

净赢家是包。

于 2016-08-30T15:44:01.057 回答
0

您可以使用数组(还要注意生成器表达式而不是列表推导):

array("f", (u for point in points for u in point)).tostring()

另一个优化是从一开始就保持点平坦。

于 2010-11-11T17:05:48.577 回答