简体   繁体   English

比较Python和R之间的函数打印

[英]Comparison of the functions print between Python and R

Python is usually much faster than R but the following code takes more time in Python than in R. Python通常比R快得多,但是下面的代码在Python中比在R中花费更多的时间。

# R
for (i in 1:10000){print(i)}
# It takes less than a second

###############################################

# Python
for i in xrange(10000):
    print i
# It takes 5 minutes!

What explain this difference? 什么解释了这个区别?

Note: The point of my question is not to know how to increase the performance of my code but "why is Python much slower than R at running this code". 注意:我的问题不是要知道如何提高代码的性能,而是“为什么Python在运行此代码时比R慢得多”。

The Verdict: 判决:

The cause for this is the printing, In python writing to stdout is quite slow when comparing with R so trying to write to the stdout 10000 TIMES! 造成这种情况的原因是打印,在写入stdout的python中与R比较时非常慢,因此尝试写入标准输出10000 in python might seem a bit slow (ignoring the range overhead) however printing it in one go reduces this gap significantly. 在python中可能看起来有点慢(忽略范围开销)但是一次打印它会显着减少这个差距。

This code is much quicker because it writes to stdout only once: 此代码更快,因为它只写入stdout一次:

lst = []

for i in range(10000):
    lst.append(i)

print lst

However this isn't because this writes to the stdout stream 10000 times: 但是这不是因为这会写入stdout流10000次:

for i in range(10000):
    print i

Also use the more memory efficient xrange() function and due to causes such as these only python 2's range() function has been replaced with the xrange() function in python 3... 另外使用内存效率更高的xrange()函数,由于这些原因,只有python 2的range()函数已被python 3中的xrange()函数替换...

It must be said that no matter what your original code only took about 5-6 seconds not 5 minutes... 必须要说的是,无论你的原始代码只用了大约5-6秒而不是5分钟......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM