在花了很多时间试图围绕多处理进行思考之后,我想出了这段代码,它是一个基准测试:
示例 1:
from multiprocessing import Process
class Alter(Process):
def __init__(self, word):
Process.__init__(self)
self.word = word
self.word2 = ''
def run(self):
# Alter string + test processing speed
for i in range(80000):
self.word2 = self.word2 + self.word
if __name__=='__main__':
# Send a string to be altered
thread1 = Alter('foo')
thread2 = Alter('bar')
thread1.start()
thread2.start()
# wait for both to finish
thread1.join()
thread2.join()
print(thread1.word2)
print(thread2.word2)
这在 2 秒内完成(多线程时间的一半)。出于好奇,我决定接下来运行这个:
示例 2:
word2 = 'foo'
word3 = 'bar'
word = 'foo'
for i in range(80000):
word2 = word2 + word
word = 'bar'
for i in range(80000):
word3 = word3 + word
print(word2)
print(word3)
令我惊恐的是,这不到半秒就跑完了!
这里发生了什么?我希望多处理运行得更快 - 鉴于示例 1 是示例 2 分为两个进程,它不应该在示例 2 的一半时间内完成吗?
更新:
在考虑了 Chris 的反馈后,我已经包含了消耗最多处理时间的“实际”代码,并引导我考虑多处理:
self.ListVar = [[13379+ strings],[13379+ strings],
[13379+ strings],[13379+ strings]]
for b in range(len(self.ListVar)):
self.list1 = []
self.temp = []
for n in range(len(self.ListVar[b])):
if not self.ListVar[b][n] in self.temp:
self.list1.insert(n, self.ListVar[b][n] + '(' +
str(self.ListVar[b].count(self.ListVar[b][n])) +
')')
self.temp.insert(0, self.ListVar[b][n])
self.ListVar[b] = list(self.list1)