Borys Bradel's Blog
Measuring elapsed time in programs
Tags: programming December 23, 2008
I recently had to measure elapsed time with subsecond accuracy in C/C++ as well as Java. Since I list a number of other languages on my resume, I figure, I'd show the approach for those as well.
C/C++
There are several approaches to show the elapsed time in seconds with subsecond accuracy in C/C++. The difference is in the functions that are called to measure time. The three functions clock(), gettimeofday(), and ftime() are probably the most popular ones. I will describe approaches using the first two functions.
The clock() function measures the amount of time that a process uses. The counter seems to start from 0 at the first call to clock(). The following is example code to measure elapsed (used) time using clock().
#include <time.h>
time_t start_time=clock();
... work ...
time_t end_time=clock();
double diff=(double)(end_time-start_time)/(double)CLOCKS_PER_SEC;
printf("%ld %ld %f\n",start_time,end_time,diff);
The gettimeofday() function measures the amount of time that has elapsed from a fixed point in time. The following is example code to measure elapsed time using gettimeofday().
#include <time.h>
#include <sys/time.h>
struct timeval start_time;
struct timeval end_time;
gettimeofday(&start_time,NULL);
... work ...
gettimeofday(&end_time,NULL);
double start_dtime=(double)start_time.tv_sec+(double)start_time.tv_usec/1000000.0;
double end_dtime=(double)end_time.tv_sec+(double)end_time.tv_usec/1000000.0; double diff=end_dtime-start_dtime;
printf("%ld %ld %f %ld %ld %f %f\n",start_time.tv_sec,start_time.tv_usec,start_dtime,end_time.tv_sec,end_time.tv_usec,end_dtime,diff);
Java
For Java the easiest approach is to use currentTimeMillis(), which is shown in the following code.
long start_time=System.currentTimeMillis()
... work ...
long end_time=System.currentTimeMillis()
double diff=(double)(end_time-start_time)/1000.0;
System.out.println(start_time+" "+end_time+" "+diff);
Perl
For perl, the following approach works well.
#! /usr/bin/perl
use Time::HiRes; my $start_time=[Time::HiRes::gettimeofday()]; ... work ... my $diff=Time::HiRes::tv_interval($start_time); print "$diff\n";
Awk
Well, unfortunately, I know of no direct way of measuring time to subsecond accuracy with awk.
Common Lisp
For common lisp, the easiest approach is (time (progn ... work ...)). There's a reason I like common lisp.
Copyright © 2008 Borys Bradel. All rights reserved. This post is only my possibly incorrect opinion.