Skip to content

Instantly share code, notes, and snippets.

@tkuchiki
Last active March 4, 2021 09:36
Show Gist options
  • Save tkuchiki/4082fec5b3360efbd5ac4ce086ce4164 to your computer and use it in GitHub Desktop.
Save tkuchiki/4082fec5b3360efbd5ac4ce086ce4164 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'time'
require 'optparse'
in_delim = "\t"
out_delim = "\t"
f = nil
opt = OptionParser.new
opt.on('--in-delimiter DELIM', 'input delimiter') do |val|
in_delim = val unless val.nil?
end
opt.on('--out-delimiter DELIM', 'output delimiter') do |val|
out_delim = val unless val.nil?
end
opt.on('-f', '--file FILEPATH', 'filepath') do |val|
f = File.open(val)
end
opt.parse(ARGV)
if f.nil?
f = STDIN
end
times = []
def hhmmss(sec)
Time.at(sec).utc.strftime("%H:%M:%S")
end
f.each do |line|
s, e = line.split(in_delim)
next if e.nil?
s.chomp!
e.chomp!
start_t = Time.parse(s)
end_t = Time.parse(e)
elapsed = (end_t - start_t)
times.push(elapsed)
puts([s, e, hhmmss(elapsed)].join(out_delim))
end
exit 1 if times.empty?
sum = times.inject(:+)
avg = (sum / times.length).to_i
puts ["max", hhmmss(times.max)].join(out_delim)
puts ["min", hhmmss(times.min)].join(out_delim)
puts ["sum", hhmmss(sum)].join(out_delim)
puts ["avg", hhmmss(avg)].join(out_delim)
$ cat test.tsv | ruby calc-elapsed-times
06:00:00        06:30:00        00:30:00
07:10:00        08:00:00        00:50:00
09:00:00        09:00:01        00:00:01
max     00:50:00
min     00:00:01
sum     01:20:01
avg     00:26:40
06:00:00 06:30:00
07:10:00 08:00:00
09:00:00 09:00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment