package MicroTime;

#    Big Sister network monitor
#    Copyright (C) 2002  Thomas Aeby
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

my $timecall = 0;
my $havehires = 0;

eval {
    require Time::HiRes;
    $havehires = 1;
};


unless( $havehires || $BigSister::common::resources{"avoid_gettimeofday_syscall"} ) {
  $timecall = 78;
  eval {
    require "sys/syscall.ph";
    undef $timecall;
    $timecall = &SYS_gettimeofday;
  };
}


sub gettimeofday {
    if( $havehires ) {
        return( Time::HiRes::time() );
    }
    return( time ) unless( $timecall );

    my $now;
    eval {
	my $TIMEVAL_T = "LL";
	my $time =  pack( $TIMEVAL_T, () );
	die "not supported" if( syscall( $timecall, $time, 0 ) == -1 );
	@time = unpack( $TIMEVAL_T, $time );
	$now = $time[0] + $time[1]/1000000;
    };
    unless( $now ) {
        undef $timecall;
	return time;
    }
    return $now;
}


sub difftime {
    my( $t1, $t2 ) = @_;

    unless( $t2 ) {
        $t2 = gettimeofday();
    }
    ($t2 += 24*3600) if( $t2 < $t1 );
    return( $t2 - $t1 );
}

1;

