Posted on 2007-04-22 20:14:07-07 by forums9
Possible problems with timing accuracy in Net::NTP
Hello PERL experts

I recently found that the system time of the LINUX system where my homepage is hosted has poor stability. It seems to be synchronized every morning, and becomes some 10 seconds late by evening.

I tried using the Net::NTP library module to measure the time offset, but that is not installed there, so I copied the source from CPAN and installed it as a module in my own CGI-BIN directory.

I wrote some code to get the "local clock offset" derived from a programming example at "http://www.webreference.com/programming/perl/ntp/2.html", but I queried two NTP servers ("ntp.metas.ch", "swisstime.ethz.ch") in sequence in my main program. I got "jitter" of 1, 2, .. sometimes to 10 seconds between the readings, and started to investigate. Then I made the following changes, and the results look much better now ( some 0.03 seconds jitter ).

Change 1: Use Time::HiRes::time() directly in the NTP module

Change 2: Do not test for "defined $CLIENT_TIME_SEND", rather call time() unconditionally; same for $CLIENT_TIME_RECEIVE:

# $CLIENT_TIME_SEND = time() unless defined $CLIENT_TIME_SEND;
$CLIENT_TIME_SEND = Time::HiRes::time();

Change 3: Before calling NTP::get_ntp_response(), my version resolves the DNS name of the time server using gethostbyaddr(). This prevents the DNS resolving time from affecting the timing later. I am still calling get_ntp_response() using its hostname (not using the IP) but at this time the DNS cache already knows the translation, and delay is negligible.

Direct Responses: Write a response
Perl Weekly newsletter
A free weekly newsletter for people who are busy to read all the blogs. click here to check it out.