在我的项目中,我将使用 GPU 而不是 CPU 在我的 Raspberry pi4 上运行 python 程序。 我尝试使用 py-videocore6 或实现我的结果,我在我的示例代码中写了这个:
from videocore6.driver import Driver
from videocore6.assembler import qpu
from time import monotonic
from hashlib import sha256
@qpu
def mine(asm, message, difficulty=1):
assert difficulty >= 1
prefix = '1' * difficulty
for i in range(10000000):
digest = sha256(str(hash(message+ str(i))).encode('utf-8'))
if digest.hexdigest().startswith(prefix):
print ("after " + str(i) + " iterations found nonce: "+ digest.hexdigest())
# This synchronization is needed between the last TMU operation and the
# program end with the thread switch just before the loop above.
barrierid(syncb, sig=thrsw)
nop()
nop()
nop(sig=thrsw)
nop(sig=thrsw)
nop()
nop()
nop(sig=thrsw)
nop()
nop()
nop()
def branch_rel_label():
with Driver() as drv:
start = monotonic()
code = drv.program(mine, "test message", 4)
X = drv.alloc((16, ), dtype = 'uint32')
Y = drv.alloc((16,), dtype = 'uint32')
unif = drv.alloc(2, dtype = 'uint32')
X[:] = np.arange(16)
Y[:] = 0.0
unif[0] = X.addresses()[0]
unif[1] = Y.addresses()[0]
drv.execute(code, unif.addresses()[0], thread=8)
end = monotonic()
print("Time elpsed: ", (end-start))
if __name__ == "__main__":
branch_rel_label()
如果我测试我的代码它会运行但是当我调用时代码会被执行
<块引用>drv.program(mine, "test message", 4)
使用普通的树莓资源,而不是在我打电话时:
<块引用>drv.execute(code, unif.addresses()[0], thread=8)
使用GPU。 为什么我的代码在 drv.program 调用而不是 drv.execute 处执行?在这种行为中,我的代码在与普通 python shell 完全相同的时间执行函数..如何使用 GPU 执行我的函数?
非常感谢
答案 0 :(得分:1)
正如我在源项目代码中快速看到的那样,带有@qpu 装饰器的函数中的所有代码都是在编译时执行的(drv.program)。 因此,在您的程序中,库函数(sha256、hexdigest 等)将在 CPU 上运行。 py-videocore6 函数(nop、add 等)也不例外,只是在 asm 中附加了 QPU 指令,生成的指令由 QPU 在 drv.execute 上执行。 所以你必须自己实现哈希函数。