/*
* timer.c
* Jason Armstrong <jason@datrix.co.za>
*
* $Id: timer.c,v 1.2 2000/01/04 22:53:10 jason Exp $
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
#include <errno.h>
#include "timer.h"
char dx_timerErrMsg[256] = "";
int
dx_startTimer(struct timeval *tvstart)
{
if (gettimeofday(tvstart, 0)) {
snprintf(dx_timerErrMsg, sizeof(dx_timerErrMsg) - 1,
"[%s:%d] gettimeofday() -> %s",
__FILE__, __LINE__,
strerror(errno));
return -1;
}
return 0;
}
char *
dx_timerStopPrint(struct timeval *tvstart, char *str, int size)
{
struct timeval tvstop;
unsigned long d, h, m;
char dc[12], hc[12], mc[12];
if (gettimeofday(&tvstop, 0)) {
snprintf(dx_timerErrMsg, sizeof(dx_timerErrMsg) - 1,
"[%s:%d] gettimeofday() -> %s",
__FILE__, __LINE__,
strerror(errno));
return (dx_timerErrMsg);
}
if ( (tvstop.tv_usec -= tvstart->tv_usec) < 0) {
--tvstop.tv_sec;
tvstop.tv_usec += DX_MILL;
}
tvstop.tv_sec -= tvstart->tv_sec;
if (!tvstop.tv_sec) {
snprintf(str, size - 1,
"%6lu µs", tvstop.tv_usec);
} else {
if ( (d = tvstop.tv_sec / DX_DAY)) {
snprintf(dc, sizeof(dc) - 1, "%2lu days ", d);
}
if ( (h = (tvstop.tv_sec / DX_HOUR) % 24)) {
snprintf(hc, sizeof(hc) - 1, "%2lu hours ", h);
}
if ( (m = (tvstop.tv_sec / DX_MIN) % 60)) {
snprintf(mc, sizeof(mc) - 1, "%2lu mins ", m);
}
if (d) {
snprintf(str, size - 1, "%s%s%s%2lu secs %6lu µs",
d ? dc : "", h ? hc : "", m ? mc : "",
tvstop.tv_sec % DX_MIN, tvstop.tv_usec);
} else if (h) {
snprintf(str, size - 1, "%s%s%2lu secs %6lu µs",
h ? hc : "", m ? mc : "",
tvstop.tv_sec % DX_MIN, tvstop.tv_usec);
} else if (m) {
snprintf(str, size - 1, "%s%2lu secs %6lu µs",
m ? mc : "",
tvstop.tv_sec % DX_MIN, tvstop.tv_usec);
} else {
snprintf(str, size - 1, "%2lu secs %6lu µs",
tvstop.tv_sec % DX_MIN, tvstop.tv_usec);
}
}
return (str);
}
syntax highlighted by Code2HTML, v. 0.9.1