python 詳解如何使用GPU大幅提高效率

cupy我覺得可以理解為cuda for numpy,安裝方式pip install cupy,假設

import numpy as np
import cupy as cp

那麼對於np.XXX一般可以直接替代為cp.XXX

其實numpy已經夠快瞭,畢竟是C寫的,每次運行的時候都會盡其所能地調用系統資源。為瞭驗證這一點,我們可以用矩陣乘法來測試一下:在形式上通過多線程並發、多進程並行以及單線程的方式,來比較一下numpy的速度和對資源的調度情況,代碼為

# th_pr_array.py
from threading import Thread
from multiprocessing import Process
from time import time as Now
import numpy as np
import sys

N = 3000

def MatrixTest(n,name,t):
    x = np.random.rand(n,n)
    x = x@x
    print(f"{name} @ {t} : {Now()-t}")

def thTest():
    t = Now()
    for i in range(5):
        Thread(target=MatrixTest,args=[N,f'th{i}',t]).start()

def prTest():
    t = Now()
    for i in range(5):
        Process(target=MatrixTest,args=[N,f'pr{i}',t]).start()

if __name__=="__main__":
    if sys.argv[1]=="th":
        thTest()
    elif sys.argv[1]=="pr":
        prTest()
    else:
        t = Now()
        for i in range(5):
            MatrixTest(N,"single",t)

運行結果為

(base) E:\Documents\00\1108>python th_pr_numpy.py th
th0 @ 1636357422.3703225 : 15.23965334892273
th1 @ 1636357422.3703225 : 17.726242780685425
th2 @ 1636357422.3703225 : 19.001763582229614
th3 @ 1636357422.3703225 : 19.06676197052002
th4 @ 1636357422.3703225 : 19.086761951446533

(base) E:\Documents\00\1108>python th_pr_numpy.py pr
pr3 @ 1636357462.4170427 : 4.031360864639282
pr0 @ 1636357462.4170427 : 4.55387806892395
pr1 @ 1636357462.4170427 : 4.590881824493408
pr4 @ 1636357462.4170427 : 4.674877643585205
pr2 @ 1636357462.4170427 : 4.702877759933472

(base) E:\Documents\00\1108>python th_pr_numpy.py single
single @ 1636357567.8899782 : 0.36359524726867676
single @ 1636357567.8899782 : 0.8137514591217041
single @ 1636357567.8899782 : 1.237830400466919
single @ 1636357567.8899782 : 1.683635950088501
single @ 1636357567.8899782 : 2.098794937133789

所以說在numpy中就別用python內置的並行和並發瞭,反而會稱為累贅。而且這麼一比更會印證numpy的強大性能。

但在cupy面前,這個速度會顯得十分蒼白,下面連續5次創建5000×5000的隨機矩陣並進行矩陣乘法,

#np_cp.py
import numpy as np
import cupy as cp
import sys
from time import time as Now

N = 5000

def testNp(t):
    for i in range(5):
        x = np.random.rand(N,N)
        x = x@x
    print(f"np:{Now()-t}")

def testCp(t):
    for i in range(5):
        x = cp.random.rand(N,N)
        x = x@x
    print(f"cp:{Now()-t}")


if __name__ == "__main__":
    t = Now()
    if sys.argv[1] == 'np':
        testNp(t)
    elif sys.argv[1]=='cp':
        testCp(t)

最後的結果是

(base) E:\Documents\00\1108>python np_cp.py np
np:8.914457082748413

(base) E:\Documents\00\1108>python np_cp.py cp
cp:0.545649528503418

而且非常霸道的是,當矩陣維度從5000×5000升到15000×15000後,cupy的計算時間並沒有什麼變化,充其量是線性增長,畢竟隻要緩存吃得下,無論多麼大的矩陣,乘法數也無非是按行或者按列增加而已。

在這裡插入圖片描述

以上就是python 詳解如何使用GPU大幅提高效率的詳細內容,更多關於Python GPU提高效率的資料請關註WalkonNet其它相關文章!

推薦閱讀: