我一生都无法找出这个问题的答案。
我编写了一个可以执行数百次繁重计算的脚本。我有一个绝妙的主意,将这些计算任务编写为 C++,然后使用 Python 的 ctypes 与它们交互。
我心想,我什至可以使用并行性进一步优化它。我最初的方法是使用线程。然后我意识到我的任务是受 CPU 限制的。因此,我们使用多处理才有意义。事实证明,多处理模块比线程慢得多,可能是由于开销所致。
然后我遇到了this http://caswenson.com/2009_06_13_bypassing_the_python_gil_with_ctypes.html。对于那些不想点击粗略链接的人来说,事实证明 ctypes 模块绕过了 GIL。这意味着我对Python线程的尝试可以实现真正的并行。
所以我的问题是:官方文档中有关于 ctypes 和 GIL 的地方吗?
我已附上用于对线程+ ctypes 和多处理进行基准测试的代码。
# Method 1: Using threading
start = time()
threads = []
for arg in args:
threads.append(threading.Thread(target=some_ctypes_func, args=(arg, )))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(f"Elapsed time: {time() - start}")
# Method 2: Using multiprocessing
results = []
with Pool(8) as p:
start = time()
for arg in args:
result = p.apply_async(some_ctypes_func, args=(arg,))
results.append(result)
results = [result.get() for result in results]
print(f"Elapsed time: {time() - start}")
使用上面的代码,线程模块比多处理快大约 2 到 3 倍。
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)