关于R与Python效率对比的问题

久闻世界上最慢的语言是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中加循环"

猜你喜欢

转载自blog.csdn.net/qq_26684561/article/details/83618854