Back - Home

PERL/CGI Program example


This program uses the Time::Hires library functions usleep(), tv_interval() in a practical example.
The CGI program checks the system clock in fractional seconds and attempts to synchronize its execution with the next full second of the system time. After this it sends a CGI response with the the local time in HH:MM:SS format.

Life Demo

This example works only on a web server where CGI programs can disable the buffering of the CGI response, or where this is already the standard setting. Modern browsers such as FireFox, Internet Explorer, ... begin rendering the website already before the full HTML page is received, so you observe a new time block every second.
Each time the loop for (my $k=0; $k < 30; $k++) the program prepares a time string, sends it to the client, then calls sleep(1). The time required for computation and data transmission is neglected.
At the end the program compares the new system time with the startup time. The difference, elapsed time, includes computation and transmission times, so this will be a little more than the nominal 30 seconds.

Complete program code
#!/usr/bin/perl -w

use CGI;
use DBI;
use POSIX qw(strftime);
use Time::HiRes qw(usleep gettimeofday tv_interval);

sub perlmain($)
my $q = new CGI;
my $t0;
my $t1;
my $t9;
  $| = 1;
## sample system clock using high resolution timer
## store as t0
  $t0 = [gettimeofday];
  print $q->header("text/html");
  print $q->start_html( -title => "Time::HiRes Demo", -bgcolor => "lightgreen" );
  print "\n";
  print $q->h2("Time::Hires Demonstration");
  ( my $sec, my $usec ) = gettimeofday();
  ## sleep until next full second
  my $correction = (1000000 - $usec);
  ## take lap time, store as t1
  $t1 = [gettimeofday];
  for (my $k=0; $k < 30; $k++)
    $timestring = strftime("%H:%M:%S",localtime(time));
    if ( $timestring =~ /9$/ )
      print "$timestring<br>\n";
      print "$timestring &nbsp;";
  # take ending time, store as t9
  ## compare ending time with lap time
  my $elapsed = tv_interval $t1,$t9;
  $elapsed = sprintf("%.3f",$elapsed);
  print $q->p ("Total time: $elapsed sec");
  print $q->end_html;

# think of crt0.0 when you see this one
my $globex = perlmain(1);
exit 0;