python - 当在多线程中使用暴力破解时,它比单线程慢

标签 python multithreading

我想列出从 0000zzzz 的 Base36 字符串的所有组合。
当我使用单线程运行它时,它的运行速度比多线程(约 13-14 秒)更快(约 6-5 秒)。
我读过here为什么使用更多线程会比使用更少线程慢。
但我有 4 个核心(8 个逻辑处理器),我认为这不是我的问题。

我的代码有问题吗?
也许 join() 函数会减慢速度?

这是我的代码:

import time
import threading

# https://codegolf.stackexchange.com/questions/169432/increment-base-36-strings?page=1&tab=votes#tab-top
def inc_base36(s):
   L,R=s[:-1],s[-1:];
   return s and[[L+chr(ord(R)+1),inc_base36(L)+'0'][R>'y'],L+'a'][R=='9']

def bruteforce(start_id, end_id):
 while start_id != end_id:
   start_id = inc_base36(start_id)

# Single thread
# --- 5.15600013733 seconds ---
start_time = time.time()
bruteforce('0000', 'zzzz')
print("--- %s seconds ---" % (time.time() - start_time))

# Two threads
# --- 13.603000164 seconds ---
t1 = threading.Thread(target=bruteforce, args = ('0000', 'hzzz')) # in decimal (0, 839807)
t2 = threading.Thread(target=bruteforce, args = ('i000', 'zzzz')) # in decimal (839808, 1679615)

start_time = time.time()
t1.start()
t2.start()
t1.join()
t2.join()
print("--- %s seconds ---" % (time.time() - start_time))

# Three threads
# --- 14.3159999847 seconds ---
t1 = threading.Thread(target=bruteforce, args = ('0000', 'bzzz')) # in decimal (0, 559871)
t2 = threading.Thread(target=bruteforce, args = ('c000', 'nzzz')) # in decimal (559872, 1119743)
t3 = threading.Thread(target=bruteforce, args = ('o000', 'zzzz')) # in decimal (1119744, 1679615)

start_time = time.time()
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
print("--- %s seconds ---" % (time.time() - start_time))

最佳答案

大多数 Python 实现都有一个 GIL(全局解释器锁),它允许一次执行一个线程。您应该使用没有 GIL 的 Jython 或在脚本中实现多处理。

关于python - 当在多线程中使用暴力破解时,它比单线程慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52026987/

相关文章:

Python:捕获特定异常

python - 有没有办法在二维数组中找到输入值的每个索引?

python - 我如何检查是否有全局或局部变量

c - 无法在线程内用 C 打印?

multithreading - 如何访问 Robolectric 中的后台线程?

Python 网页中的 Javascript 事件处理程序不起作用

python - 如何使用 Python 从最高到最低设置 k-Means 聚类标签?

multithreading - C++/CX中的任务上的.wait()引发异常

python - 如何从 QThread 和 Queue 运行的函数返回值

multithreading - 如何编写单元测试来检查方法是否线程安全