From 96809417fcceb13c83caa6b16d8174ea209bce27 Mon Sep 17 00:00:00 2001 From: Ben Leinweber Date: Mon, 30 Oct 2017 08:24:47 -0700 Subject: [PATCH] ts: Introduce '-m' option to use CLOCK_MONOTONIC The new '-m' option will retrieve the monotonic clock rather than the realtime clock. Sometimes it is required that the timer being used not change even when the user updates the system time. The monotonic clock guarantees a monotonically increasing time value which may not be adjusted. Signed-off-by: Ben Leinweber --- ts | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/ts b/ts index 63baf18..7f6ff85 100755 --- a/ts +++ b/ts @@ -56,8 +56,9 @@ $|=1; my $rel=0; my $inc=0; my $sincestart=0; +my $mono=0; use Getopt::Long; -GetOptions("r" => \$rel, "i" => \$inc, "s" => \$sincestart) || die "usage: ts [-r] [-i | -s] [format]\n"; +GetOptions("r" => \$rel, "i" => \$inc, "s" => \$sincestart, "m" => \$mono) || die "usage: ts [-r] [-i | -s] [format]\n"; if ($rel) { eval q{ @@ -77,15 +78,20 @@ $format=shift if @ARGV; # For subsecond resolution, Time::HiRes is needed. my $hires=0; -if ($format=~/\%\.[Ss]/) { +if ($format=~/\%\.[Ss]/ || $mono) { require Time::HiRes; + use Time::HiRes qw(CLOCK_MONOTONIC); $hires=1; } my $lastseconds = 0; my $lastmicroseconds = 0; -if ($hires) { +if ($mono) { + my $raw_time = Time::HiRes::clock_gettime(CLOCK_MONOTONIC); + $lastseconds = int($raw_time); + $lastmicroseconds = int(1000000 * ($raw_time - $lastseconds)); +} elsif ($hires) { ($lastseconds, $lastmicroseconds) = Time::HiRes::gettimeofday(); } else { $lastseconds = time; @@ -96,7 +102,17 @@ while (<>) { if (! $rel) { if ($hires) { my $f=$format; - my ($seconds, $microseconds) = Time::HiRes::gettimeofday(); + my $seconds; + my $microseconds; + if ($mono) { + my $raw_time = + Time::HiRes::clock_gettime(CLOCK_MONOTONIC); + $seconds = int($raw_time); + $microseconds = int(1000000 * ($raw_time - $seconds)); + } else { + ($seconds, $microseconds) = Time::HiRes::gettimeofday(); + } + if ($inc || $sincestart) { my $deltaseconds = $seconds - $lastseconds; my $deltamicroseconds = $microseconds - $lastmicroseconds; -- 2.11.4.GIT