简体   繁体   English

在Cython中迭代对象列表/集合的最快方法?

[英]Fastest way to iterate through a list/collection of objects in Cython?

I have this code for a neural network library I am building 我有我正在构建的神经网络库的代码

for connection in self.backwardConnections:
    self._z += connection.value()

where connection is a cdef class Connection and backwardConnections is python list of connections. 其中connectioncdef class ConnectionbackwardConnections cdef class Connection是python连接list

I have two question 我有两个问题

  1. What is the fastest iterate through a Python list? 通过Python列表进行最快的迭代是什么? (I could have also done it with the typical for int i in range (len (..)) ) (我也可以使用for int i in range (len (..))的典型值完成此操作)
  2. If I abandon the python list approach, what collection type (eg numpy array, c++ vectors, etc) could hold my Connection objects and improve performance? 如果我放弃python列表方法,哪种收集类型(例如numpy数组,c ++矢量等)可以容纳我的Connection对象并提高性能?

The for ... in ...: construction is the fastest way to iterate over a list in Python. for ... in ...:构造是迭代Python中列表的最快方法。 You will also not significantly improve performance by switching to another data type. 通过切换到另一种数据类型,您也不会显着提高性能。 These two things are already very fast. 这两件事已经非常快了。

My guess is that you are going about optimizing this code the wrong way. 我的猜测是您将以错误的方式优化此代码。 Instead of looking at the looping mechanism, which likely takes up an insignificant fraction of your running time, why not look at optimizing whatever the call to .value() does? 与其着眼于可能花费很少的运行时间的循环机制,不如不着眼于优化对.value()的调用?

There's also the possibility that Python is just too slow for what you're trying to do. Python可能对于您尝试执行的操作来说太慢了。 I find such cases to be quite rare, though. 我发现这种情况很少见。

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

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