關於R與Python效率對比的問題
阿新 • • 發佈:2018-11-05
久聞世界上最慢的語言是Python, 比Python還要慢的語言是R
聽聞numpy是舉世聞名的高效科學計算庫?
來我們來看看100萬次迴圈後的結果...
Python
import numpy as np import matplotlib.pyplot as plt import time hot='4 5 5 6 7 7 7 8 8 8 9 11 11 12 12 13 13 13 13 14 14 14 16 16 17 \ 17 18 18 21 21' hot=hot.split() hot=np.float64(hot)#型別轉換 d=[] import time start=time.clock() for i in range(1000000): index=np.random.choice(30,15,replace=False)#取隨機數 d.append(np.mean(hot[index])-np.mean(hot[hot!=hot[index]]))#求隨機數的均值減去剩下的數的均值 plt.hist(d)#直方圖 end=time.clock() print(end-start)
R
hot='4 5 5 6 7 7 7 8 8 8 9 11 11 12 12 13 13 13 13 14 14 14 16 16 17 17 18 18 21 21'
hot=str_split(hot,' ')
hot=as.numeric(hot[[1]])#轉換資料型別
s=Sys.time()
result=c()
for(i in 1:1000000){
index=sample(30,15,F)
result[i]=mean(hot[index])-mean(hot[-index])
}
hist(result)
e=Sys.time()
print(e-s)
結果是Python基於高效科學計算包numpy的時間是66秒, 而R是18秒
Python的迴圈是真的傷不起, 哪位大師說過這樣一句話
"我寧願做任何事情,也不願在python中加迴圈"