| 1 | #!/usr/bin/env perl | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use Time::Nanos; | ||
| 5 | use v5.16; | ||
| 6 | |||
| 7 | printf("Using %s %s\n\n", color('white', 'Time::Nanos'), color(228, $Time::Nanos::VERSION)); | ||
| 8 | |||
| 9 | ################################################################################ | ||
| 10 | |||
| 11 | #Time::Nanos::clock_source('monotonic'); | ||
| 12 | my $st = stopwatch(1); | ||
| 13 | |||
| 14 | for (1 .. 4) { | ||
| 15 | my $ns = nanos(); | ||
| 16 | printf "%s nanoseconds\n", $ns; | ||
| 17 | } | ||
| 18 | |||
| 19 | print "\n"; | ||
| 20 | |||
| 21 | for (1 .. 4) { | ||
| 22 | my $us = micros(); | ||
| 23 | printf "%s microseconds\n", $us; | ||
| 24 | } | ||
| 25 | |||
| 26 | print "\n"; | ||
| 27 | |||
| 28 | for (1 .. 4) { | ||
| 29 | my $ms = millis(); | ||
| 30 | printf "%s milliseconds\n", $ms; | ||
| 31 | } | ||
| 32 | |||
| 33 | my $total = stopwatch(); | ||
| 34 | print "\n"; | ||
| 35 | printf("Script executed in %d ns\n", $total); | ||
| 36 | |||
| 37 | ################################################################################ | ||
| 38 | ################################################################################ | ||
| 39 | |||
| 40 | # String format: '115', '165_bold', '10_on_140', 'reset', 'on_173', 'red', 'white_on_blue' | ||
| 41 | sub color { | ||
| 42 | my ($str, $txt) = @_; | ||
| 43 | |||
| 44 | if (-t STDOUT == 0 || $ENV{NO_COLOR}) { return $txt // ""; } # No interactive terminal | ||
| 45 | if (!length($str) || $str eq 'reset') { return "\e[0m"; } # No string = RESET | ||
| 46 | |||
| 47 | # Some predefined colors/commands | ||
| 48 | my %color_map = qw(red 160 blue 27 green 34 yellow 226 orange 214 purple 93 white 15 black 0); | ||
| 49 | my %cmd_map = qw(bold 1 italic 3 underline 4 blink 5 inverse 7); | ||
| 50 | |||
| 51 | # Pre-process the string. | ||
| 52 | $str =~ s/on_/-/; # "on_" becomes a negative number | ||
| 53 | $str =~ s|([A-Za-z]+)|$color_map{$1} // $1|eg; # command number | ||
| 54 | |||
| 55 | my @parts = split("_", $str); | ||
| 56 | foreach my $p (@parts) { | ||
| 57 | my $cmd_num = $cmd_map{$p // 0}; | ||
| 58 | |||
| 59 | if ($cmd_num) { $p = $cmd_num; } | ||
| 60 | elsif (defined($p) && $p =~ /^-(.+)/) { $p = "48;5;$p"; } | ||
| 61 | elsif (defined($p)) { $p = "38;5;$p"; } | ||
| 62 | } | ||
| 63 | |||
| 64 | my $ret = "\e[" . join(";", @parts) . "m"; | ||
| 65 | |||
| 66 | if (defined($txt)) { $ret .= $txt . "\e[0m"; } | ||
| 67 | |||
| 68 | return $ret; | ||
| 69 | } | ||
| 70 | |||
| 71 | # Stopwatch(1) = start | ||
| 72 | # Stopwatch() = return ns from start time | ||
| 73 | sub stopwatch { | ||
| 74 | my $start = shift(); | ||
| 75 | state $last_start = undef; | ||
| 76 | my $ret; | ||
| 77 | |||
| 78 | if ($start) { | ||
| 79 | $last_start = nanos(); | ||
| 80 | $ret = $last_start; | ||
| 81 | } else { | ||
| 82 | $ret = nanos() - $last_start; | ||
| 83 | } | ||
| 84 | |||
| 85 | return $ret; | ||
| 86 | } |