time.pl 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env perl
  2. use strict;
  3. use warnings;
  4. use Config;
  5. if (@ARGV < 2) {
  6. die "Usage: $0 <prefix> <command...>\n";
  7. }
  8. sub gettime {
  9. my ($sec, $usec);
  10. eval {
  11. require Time::HiRes;
  12. ($sec, $usec) = Time::HiRes::gettimeofday();
  13. };
  14. unless (defined($sec) && defined($usec)) {
  15. my $tv_t = ($Config{'longsize'} == 8) ? 'qq' : 'll';
  16. my $tv = pack $tv_t, 0, 0;
  17. eval {
  18. require 'syscall.ph';
  19. syscall(SYS_gettimeofday(), $tv, 0);
  20. };
  21. ($sec, $usec) = unpack $tv_t, $tv;
  22. }
  23. return ($sec, $usec);
  24. }
  25. my ($prefix, @cmd) = @ARGV;
  26. my ($sec, $usec) = gettime();
  27. my $pid = fork();
  28. if (!defined($pid)) {
  29. die "$0: Failure to fork(): $!\n";
  30. }
  31. elsif ($pid == 0) {
  32. exec(@cmd);
  33. die "$0: Failure to exec(): $!\n";
  34. }
  35. else {
  36. $SIG{'INT'} = 'IGNORE';
  37. $SIG{'QUIT'} = 'IGNORE';
  38. if (waitpid($pid, 0) == -1) {
  39. die "$0: Failure to waitpid(): $!\n";
  40. }
  41. my $exitcode = $? >> 8;
  42. my ($sec2, $usec2) = gettime();
  43. my (undef, undef, $cuser, $csystem) = times();
  44. printf STDOUT "%s#%.2f#%.2f#%.2f\n",
  45. $prefix, $cuser, $csystem,
  46. ($sec2 - $sec) + ($usec2 - $usec) / 1000000;
  47. $SIG{'INT'} = 'DEFAULT';
  48. $SIG{'QUIT'} = 'DEFAULT';
  49. exit $exitcode;
  50. }