7

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,

3
  • My suggestion is, test and measure it... anyway from my experience, heavy printing (obviously) slows down the execution, and in particular in RStudio I found some problem when the console is full of printed text
    – digEmAll
    Jun 28, 2016 at 21:21
  • 1
    You could consider printing in steps instead of each iteration -- i.e. if((i %% step) == 0) print() to avoid multiple calls to print which is, also, a function and -depending on the method dispatched- can be time consuming.
    – alexis_laz
    Jun 28, 2016 at 22:23
  • Every function call takes time and printing is a rather expensive function call. However, often this additional time is not relevant, because if you feel the need to show progress you either have written extremely inefficient code anyway (i.e., you should be using vectorized functions or a different algorithm) or you do something that is necessarily so slow that the small additional time for printing is negligible in comparison.
    – Roland
    Jun 29, 2016 at 7:43

2 Answers 2

6

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?

1
  • 1
    I would use message instead of print to display the iteration. In fact, when developing codes for others this is recommended since you can use suppressMessages then.
    – Roland
    Jun 29, 2016 at 7:32
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.