1

If I do:

sleep 1 

versus

sleep 1 & wait $!

will there be any difference in terms of CPU usage for spawning a foreground process versus a background process? Or will the performance of both lines be exactly equal?

2 Answers 2

1

With both commands, the shell will 1/ create a parallel subprocess which executes sleep, 2/tell the OS… put the shell process on pause until the sleep process ends. Then the performances are equal.

0

Yes.

On my system the first takes 3.0 ms and the second takes 3.3 ms CPU time.

In practice I would never worry about the 0.3 ms CPU time if you are sleeping a full second.

The 0.3 ms is probably caused by the extra fork that is needed to put sleep in the background. In other words: It is a one-time cost, not a 10% extra cost for running jobs in the background.

2
  • 1
    I added that sleep command just as an example for the script, I ment the question more in general. Is your 0.3 ms difference caused purely by the extra wait command, or are there other reasons?
    – Maestro
    Apr 19, 2023 at 21:44
  • Can you explain the extra fork. I don't think that is obvious. Can you also describe how you measured the difference? Apr 20, 2023 at 7:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .