多处理模块对于python初学者来说非常困惑,特别是那些刚刚从MATLAB迁移并且使用并行计算工具箱变得懒惰的人.我有以下功能需要大约80秒运行,我想通过使用Python的多处理模块来缩短这个时间.
from time import time
xmax = 100000000
start = time()
for x in range(xmax):
y = ((x+5)**2+x-40)
if y <= 0xf+1:
print('Condition met at: ', y, x)
end = time()
tt = end-start #total time
print('Each iteration took: ', tt/xmax)
print('Total time: ', tt)
Run Code Online (Sandbox Code Playgroud)
这按预期输出:
Condition met at: -15 0
Condition met at: -3 1
Condition met at: 11 2
Each iteration took: 8.667453265190124e-07
Total time: 86.67453265190125
Run Code Online (Sandbox Code Playgroud)
由于循环的任何迭代都不依赖于其他循环,我尝试从官方文档中采用此服务器进程来在单独的进程中扫描范围的块.最后我想出了vartec对这个问题的回答,可以准备以下代码.我还根据Darkonaut对当前问题的回答更新了代码.
from time import time
import multiprocessing as …Run Code Online (Sandbox Code Playgroud) python parallel-processing multiprocessing python-3.x python-multiprocessing
下面的代码hashlib.sha256()与我sha256_test()用原始 python 编写的函数在哈希率性能方面进行了比较。
from time import time_ns as time\nimport hashlib\n\ndef pad512(bytes_):\n L = len(bytes_)*8\n K = 512 - ((L + 1) % 512)\n padding = (1 << K) | L\n return bytes_ + padding.to_bytes((K + 1)//8, \'big\')\n\ndef mpars (M):\n chunks = []\n while M:\n chunks.append(M[:64])\n M = M[64:]\n return chunks\n\ndef sha256_transform(H, Kt, W):\n a, b, c, d, e, f, g, h = H\n # Step 1: Looping\n for t in range(0, 64):\n T1 = h …Run Code Online (Sandbox Code Playgroud) 我是python的新手,只是想知道内存分配是如何工作的.事实证明,测量存储变量大小的一种方法是使用sys.getsizeof(x)它,它将返回x内存中占用的字节数,对吧?以下是示例代码:
import struct
import sys
x = struct.pack('<L', 0xffffffff)
print(len(x))
print(sys.getsizeof(x))
Run Code Online (Sandbox Code Playgroud)
这使:
4
37
Run Code Online (Sandbox Code Playgroud)
x我刚刚创建的变量是一个4字节的字符串,第一个问题就出现了.为什么分配给4字节字符串的内存是37字节?这不是太多额外的空间吗?
当我开始创建一个2*4字节字符串列表时,故事变得更加复杂.贝娄,你会发现另外几行:
import struct
import sys
k = 2
rng = range(0, k)
x = [b''] * k
for i in rng:
x[i] = struct.pack('<L', 0xffffffff)
print(len(x))
print(len(x[0]))
print(sys.getsizeof(x))
print(sys.getsizeof(x[0]))
Run Code Online (Sandbox Code Playgroud)
从中得到:
2
4
80
37
Run Code Online (Sandbox Code Playgroud)
另一个问题是,为什么当我在列表中存储两个4字节字符串时,分配给它们的内存总和不等于它们的独奏大小的总和?!那是37 + 37 != 80.那些额外的6个字节是什么?
让我们放大k到10000,以前的代码得到:
10000
4
80064
37
Run Code Online (Sandbox Code Playgroud)
在将独奏大小与整体进行比较时,差异显着增加:37 * 10000 = 370000 != 80064 …