Remi.b
Remi.b

Reputation: 18219

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.

# 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".

Upvotes: 0

Views: 130

Answers (1)

Deelaka
Deelaka

Reputation: 13693

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! in python might seem a bit slow (ignoring the range overhead) however printing it in one go reduces this gap significantly.

This code is much quicker because it writes to stdout only once:

lst = []

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

print lst

However this isn't because this writes to the stdout stream 10000 times:

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...

It must be said that no matter what your original code only took about 5-6 seconds not 5 minutes...

Upvotes: 2

Related Questions