[英]Is it possible to parallelize this loop in python?
我一直在開發一個程序來獲取彩虹表,使用 crc32 哈希。
程序的主循環如下:
from zlib import crc32
from string import ascii_lowercase
from itertools import product
...
rt = {}
i = 0
for p in product(ascii_lowercase, repeat = 8):
i += 1
print('\n%d' % i)
p = ''.join(p)
print('\nCurrent password = %s' % p)
r = bytes(p, 'utf-8')
h = hex(crc32(r))
for j in range(2**20):
h = list(h)
del h[0]
del h[0]
for k in range(0, len(h)):
if (h[k].isdigit()):
h[k] = chr(ord(h[k]) + 50)
h = ''.join(h)
r = bytes(h, 'utf-8')
h = hex(crc32(r))
h = list(h)
del h[0]
del h[0]
h = ''.join(h)
print('\nFinal hash = %s\n' % h)
rt[p] = h
if (i == 2**20):
break
因此,代碼按照我的預期工作,當它退出循環時,它將生成的彩虹表(變量 rt)存儲到內存中。 好吧,以上面代碼中顯示的當前迭代次數,完成它的執行需要幾天時間,我需要創建這個表,以及通過循環進行不同迭代的其他表,以便對他們。
我認為嘗試並行化它是一個好主意,但是在閱讀了關於多處理的文檔並潛伏在一些關於它的帖子之后,我仍然無法以正確的方式並行化它。
提前致謝!
嘗試這個:
from zlib import crc32
from string import ascii_lowercase
from itertools import product
from multiprocessing.pool import Pool
def table(p):
p = ''.join(p)
r = bytes(p, 'ascii')
h = hex(crc32(r))
for j in range(2**20):
h = list(h)
del h[0]
del h[0]
for k in range(0, len(h)):
if (h[k].isdigit()):
h[k] = chr(ord(h[k]) + 50)
h = ''.join(h)
r = bytes(h, 'ascii')
h = hex(crc32(r))
h = list(h)
del h[0]
del h[0]
h = ''.join(h)
return (p, h)
if __name__ == "__main__":
rt = {}
i = 0
with Pool(4) as pool:
for p, h in pool.imap_unordered(table, product(ascii_lowercase, repeat = 8)):
print('\n%d' % i)
print('\nCurrent password = %s' % p)
print('\nFinal hash = %s\n' % h)
i += 1
rt[p] = h
if i == 2**20:
break
請注意,由於計算任務的任意順序,最終中斷條件i == 2**20
可能會不准確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.