几周前,我问了一个关于提高用 Python 编写的函数的速度的问题。当时,TryPyPy 让我注意到了使用 Cython 这样做的可能性。他还好心地举了一个例子,说明我如何对那个代码片段进行 Cythonize。我想对下面的代码做同样的事情,看看我可以通过声明变量类型来多快。我有几个与此相关的问题。我在 cython.org 上看过教程,但我仍有一些问题。它们密切相关:
- 我不懂任何 C。我需要学习哪些部分才能使用 Cython 声明变量类型?
- python列表和元组对应的C类型是什么?例如,我可以
double
在 Cythonfloat
中使用 Python 中的 for。我要为列表做什么?一般来说,我在哪里可以找到给定 Python 类型对应的 C 类型。
任何关于我如何对下面的代码进行 Cythonize 的示例都会非常有帮助。我在代码中插入了注释,提供有关变量类型的信息。
class Some_class(object):
** Other attributes and functions **
def update_awareness_status(self, this_var, timePd):
'''Inputs: this_var (type: float)
timePd (type: int)
Output: None'''
max_number = len(self.possibilities)
# self.possibilities is a list of tuples.
# Each tuple is a pair of person objects.
k = int(math.ceil(0.3 * max_number))
actual_number = random.choice(range(k))
chosen_possibilities = random.sample(self.possibilities,
actual_number)
if len(chosen_possibilities) > 0:
# chosen_possibilities is a list of tuples, each tuple is a pair
# of person objects. I have included the code for the Person class
# below.
for p1,p2 in chosen_possibilities:
# awareness_status is a tuple (float, int)
if p1.awareness_status[1] < p2.awareness_status[1]:
if p1.value > p2.awareness_status[0]:
p1.awareness_status = (this_var, timePd)
else:
p1.awareness_status = p2.awareness_status
elif p1.awareness_status[1] > p2.awareness_status[1]:
if p2.value > p1.awareness_status[0]:
p2.awareness_status = (price, timePd)
else:
p2.awareness_status = p1.awareness_status
else:
pass
class Person(object):
def __init__(self,id, value):
self.value = value
self.id = id
self.max_val = 50000
## Initial awareness status.
self.awarenessStatus = (self.max_val, -1)