一个相对简单的问题:
如果我将一个受 CPU 限制的瓶颈方法从 Python 转换为 C 扩展(大致实现相同的算法),
- 我应该期望速度和性能提高多少?
- 是什么因素决定的?
更新:人们似乎在抱怨缺乏细节。我主要是想了解哪些因素会使一段 Python 代码成为用 C 重写的良好候选者(即,如果原始 Python 受 CPU 限制,那么何时移植到 C 实际上会提高速度)。
具体来说,这是我正在查看的一段代码。基本上它是一种递归方法,它采用两个列表列表(“列”列表,其中每列包含可能进入该列的可能值......基本上是一个模式),并查看是否有可能使小于 n (通常是 1)更改(其中更改可能是向列添加新值、添加新列、删除列等),以便您有一些值序列(每列中的一个值)可以从任一模式构建。它在精神上与计算字符串之间的编辑距离非常相似。这是代码:
def CheckMerge(self, schemai, schemaj, starti, startj, \
changesLeft, path):
# if starti == 0 and startj == 0:
# print '\n'
# print schemai.schema
# print ''
# print schemaj.schema
if starti == len(schemai.schema) and startj == len(schemaj.schema):
return (True, path)
if starti < len(schemai.schema):
icopy = schemai.schema[starti]
else:
icopy = []
if startj < len(schemaj.schema):
jcopy = schemaj.schema[startj]
else:
jcopy = []
intersect = set(icopy).intersection(set(jcopy))
intersect.discard('')
if len(intersect) == 0:
if starti < len(schemai.schema) and \
('' in schemai.schema[starti] or changesLeft > 0):
if not '' in schemai.schema[starti]:
changesLeft -= 1
changesCopy = list(path)
changesCopy.append('skipi')
result,steps = self.CheckMerge(schemai, schemaj, starti+1, startj, \
changesLeft, changesCopy)
if result:
return (result,steps)
elif not '' in schemai.schema[starti]:
changesLeft += 1
if startj < len(schemaj.schema) and \
('' in schemaj.schema[startj] or changesLeft > 0):
if not '' in schemaj.schema[startj]:
changesLeft -= 1
changesCopy = list(path)
changesCopy.append('skipj')
result,steps = self.CheckMerge(schemai, schemaj, starti, startj+1, \
changesLeft, changesCopy)
if result:
return (result, steps)
elif not '' in schemaj.schema[startj]:
changesLeft += 1
if changesLeft > 0:
changesCopy = list(path)
changesCopy.append('replace')
changesLeft -= 1
result,steps = self.CheckMerge(schemai, schemaj, starti+1, startj+1, \
changesLeft, changesCopy)
if result:
return (result, steps)
return (False, None)
else:
changesCopy = list(path)
changesCopy.append('merge')
result,steps = self.CheckMerge(schemai, schemaj, starti+1, startj+1, \
changesLeft, changesCopy)
if result:
return (result, steps)
else:
return (False, None)