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,
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.
message
instead of print
to display the iteration. In fact, when developing codes for others this is recommended since you can use suppressMessages
then.
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!!!!!
print
ing in steps instead of each iteration -- i.e.if((i %% step) == 0) print()
to avoid multiple calls toprint
which is, also, a function and -depending on the method dispatched- can be time consuming.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.