/*
Function:  fractiontime.c
Version:   1.0.0
Date:      31-MAY-2002
Author:    David Mathog, Biology Division, Caltech
email:     mathog@caltech.edu
Copyright: 2002 David Mathog and California Institute of Technology (Caltech)

Description:

    A handy function for profiling the time spent in various sections
    of code.  Requires:
    
       #include <sys/times.h>    

Example:
    The first call below initializes, the last call emits results
    to stderr, and everything else adds time to the accumulator.
    
      fractiontime(-16);
      code...
         while(1){
           fractiontime(4);
           code...
           fractiontime(5);
           code...
           fractiontime(6);
           code...
         }
      code...
      fractiontime(16);
      fractiontime(-1);

License terms:
    You may run this program on any platform. You may
    redistribute the source code of this program subject to
    the condition that you do not first modify it in any way.
    You may  distribute binary versions of this program so long
    as they were compiled from unmodified source code.  There
    is no charge for using this software.  You may not charge
    others for the use of this software.

*/

void fractiontime(int interval){
static clock_t last;
static clock_t *intervals=NULL;
static int size=0;
clock_t now;
struct tms thetms;
double seconds;
int i;

   now=times(&thetms);
   
   if(interval < 0){  /* initialize all interval counts */
     if(size==0){
       size = -1 * interval;
       intervals=malloc(sizeof(clock_t)*size);
       if(intervals==NULL){
         (void) fprintf(stderr,"fractiontime fatal error: could not allocate memory\n");
         exit(EXIT_FAILURE);
       }
       for (i=0;i<size;i++){
         intervals[i]=(clock_t) 0;
       }
       last =now;
     }
     else {  /* emit results to stderr */
       for(now=0,i=0;i<size;i++){
         now += intervals[i];
       }
       if(now==(clock_t) 0)return;
       for(i=0;i<size;i++){
          seconds = intervals[i];
          seconds /= (double) now;
          if(seconds < .000001)seconds=0.0;
         (void) fprintf(stderr,"Interval: %3.3d Fraction: %8.6f\n",i,seconds);
       }
     }
   }
   else {
     if(intervals==NULL)return;  /* bad mistake, but just return */
     intervals[interval] += (last - now);
     last = now;
   }
}
