user3285014
user3285014

Reputation: 319

Saving elapsed time for each forked process in bash

I am running six process in parallel, each takes different time to complete. My goal is to simply record the time each of the process takes to complete.

Below is an example:

  1 #!/bin/bash
  2 
  3  { time sleep 30  > /dev/null 2>&1 ; } 2>> testing_time &
  4  PID1=$!
  5 { time sleep 100  > /dev/null 2>&1 ; } 2>> testing_time &
  6  PID2=$!
  7 
  8  wait $PID2
  9  echo "PID2 end" >> testing_time
 10 
 11  wait $PID1
 12  echo "PID1 end" >> testing_time

The output I get is:

real    0m30.032s
user    0m0.001s
sys     0m0.003s

real    1m40.025s
user    0m0.001s
sys     0m0.003s
PID2 end
PID1 end

The problem is, when I have many processes, I don't really know which time corresponds to which process. I am hoping to get some output which shows the elapsed time (only real time is fine too) of the process with some comments indicating which process the time corresponds to.

Expected output:

PID1 starts
real    0m30.032s
user    0m0.001s
sys     0m0.003s
PID1 end

PID2 starts
real    1m40.025s
user    0m0.001s
sys     0m0.003s
PID2 end
PID1 end

Upvotes: 0

Views: 42

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295679

One reasonable approach is to set the TIMEFORMAT variable to include your command.

time_silent_cmd() {
  local TIMEFORMAT cmd

  printf -v cmd '%q ' "$@"
  TIMEFORMAT="%R used for ${cmd//%/%%}"
  time { "$@" >/dev/null 2>&1 ; }
}

{
  time_silent_cmd sleep 0.5 &
  time_silent_cmd sleep 0.3 &
  time_silent_cmd printf '%s\n' "Sample with a % sign"
} 2>testing_time
wait

leaves the testing_time file containing contents akin to:

0.000 used for printf %s\\n Sample\ with\ a\ %\ sign
0.305 used for sleep 0.3
0.504 used for sleep 0.5

...on which point -- if you copy-and-paste that printf command to a prompt, the quoting generated by %q is such that it evaluates to its literal contents.

Upvotes: 3

Related Questions