为什么此功能不能从多线程中受益?

时间:2018-12-02 12:15:56

标签: python multithreading multiprocessing python-multithreading public-key-encryption

有人知道为什么功能1比功能2花费更长的时间,即使功能1是多线程的,并且应该比功能2更好地使用系统资源吗? 我真的不知道在实施多处理时是否以及在哪里出错。

功能1:

def encrypt(message, keyname="publicKey.rsa"):
"""
Encrypts or decrypts a hex message.
:param message: Must be a hexadecimal number. Example: 3e40f3ad, not: 0x3e40f3ad
:param keyname: Must be the name of the keyfile in the RSA-420 path.
:return: Returns encrypted or decrypted hexadecimal string (Example: "4723d8ea") with spaces as block splitters.
"""
crypted = ""
key = readkey(keyname)
exp, mod = format(int(key[0], 16), "x"), format(int(key[1], 16), "x")
blocklength = len(mod) - 1
blockcount = int(math.ceil(len(message)/blocklength))
results = []
pool = tp(processes=6)
for i in range(blockcount-1):
    results.append(None)
for i in range(blockcount-1):
    part = message[i*blocklength:((i+1)*blocklength)]
    res = pool.apply_async(crypt, args=(int(part, 16), int(exp, 16), int(mod, 16)))
    results[i] = res.get()
for i in range(len(results)):
    crypted += format(results[i], "x") + " "
i = blockcount-1
part = message[i*blocklength:((i+1)*blocklength)]
lastlen = len(part)
crypted += format(pow(int(part, 16), int(exp, 16), int(mod, 16)), "x") + " "
return crypted + str(blocklength) + " " + str(lastlen)

功能2:

def encryptold(message, keyname="publicKey.rsa"):
"""
Encrypts or decrypts a hex message.
:param message: Must be a hexadecimal number. Example: 3e40f3ad, not: 0x3e40f3ad
:param keyname: Must be the name of the keyfile in the RSA-420 path.
:return: Returns encrypted or decrypted hexadecimal string (Example: "4723d8ea") with spaces as block splitters.
"""
crypted = ""
key = readkey(keyname)
exp, mod = format(int(key[0], 16), "x"), format(int(key[1], 16), "x")
blocklength = len(mod) - 1
blockcount = math.ceil(len(message)/blocklength)
for i in range(blockcount-1):
    part = message[i*blocklength:((i+1)*blocklength)]
    crypted += format(pow(int(part, 16), int(exp, 16), int(mod, 16)), "x") + " "
i = blockcount-1
part = message[i*blocklength:((i+1)*blocklength)]
lastlen = len(part)
crypted += format(pow(int(part, 16), int(exp, 16), int(mod, 16)), "x") + " "
return crypted + str(blocklength) + " " + str(lastlen)

我测试了用两种代码对206kB文件进行加密的过程,尽管由于我的系统具有6个物理核心,所以多线程文件的速度也要慢600%,尽管它应该快600%。

感谢您的提前帮助!

0 个答案:

没有答案