Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia waits for function to finish before printing message in a loop

I have a function in Julia that requires to do things in a loop. A parameter is passed to the loop, and the bigger this parameter, the slower the function gets. I would like to have a message to know in which iteration it is, but it seems that Julia waits for the whole function to be finished before printing anything. This is Julia 1.4. That behaviour was not on Julia 1.3. A example would be like this

function f(x)
   rr=0.000:0.0001:x
   aux=0
   for r in rr
      print(r, " ")
      aux+=veryslowfunction(r)
   end
  return aux
end

As it is, f, when called, does not print anything until it has finished.

like image 477
wpkzz Avatar asked Apr 01 '20 23:04

wpkzz


2 Answers

You need to add after the print command:

flush(stdout)

Explanation

The standard output of a process is usually buffered. The particular buffer size and behavior will depend on your system setting and perhaps the terminal type. By flushing the buffer you make sure that the contents is actually sent to the terminal.

like image 147
Przemyslaw Szufel Avatar answered Sep 28 '22 08:09

Przemyslaw Szufel


Alternatively, you can also use a library like ProgressLogging.jl (needs TerminalLoggers.jl to see actual output), or ProgressMeter.jl, which will automatically update a nicely formatted status bar during each step of the loop.

For example, with ProgressMeter, a call to

function f(x)
   rr=0.000:0.0001:x
   aux=0
   @showprogress for r in rr
      aux += veryslowfunction(r)
   end
  return aux
end

will show something like (in the end):

Progress: 100%|██████████████████████████████████████████████████████████████| Time: 0:00:10
like image 29
phipsgabler Avatar answered Sep 28 '22 08:09

phipsgabler