Fredkho
Fredkho

Reputation: 578

R: Does the use of the print function inside a for loop slow down R

In R, inside a for loop, I am using the function print to display on the Rstudio console the iteration of the for loop. Will this slow down my code or not?

Based on experience I would say that yes but I have no rationale behind that. Thanks,

Upvotes: 7

Views: 3640

Answers (2)

F.C. Saviour
F.C. Saviour

Reputation: 31

it has a great impact on the speed of execution

for example i was training a machine learning model in octave 8th gen i5 intel processor 8gb ram with print inside loop the speed was 76 training examples per second but after removing print statement it became 1000 training examples per second

for one loop there was 14000 examples it really saves huge time!!!!!

Upvotes: 3

Benjamin
Benjamin

Reputation: 17369

It will almost certainly slow down your code, but by how much is the question. If you are printing small objects, such as integers, you probably won't notice much impact. If you print large dataframes, it could be very noticeable.

If you really must print, try to use the appropriate method. For example, use print.data.frame instead of just print.

My experience has been that printing in a loop is usually only necessary when I want to output plots or tables to a document. Otherwise, it usually only has value for observing and diagnosing issues that may occur in your loop.

See also Is it safe to assume the performance difference between implicit and explicit print is related to object size?

Upvotes: 6

Related Questions