stopwatch.c
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00038 #include "fastlib/fx/stopwatch.h"
00039
00040
00041 #include "fastlib/base/debug.h"
00042
00043 #include <unistd.h>
00044 #include <time.h>
00045 #include <sys/time.h>
00046
00047
00048
00049
00050
00051 void timestamp_init(struct timestamp *dest)
00052 {
00053 memset(dest, 0, sizeof(struct timestamp));
00054 }
00055
00056 void timestamp_add(struct timestamp *dest, const struct timestamp *src)
00057 {
00058 dest->micros += src->micros;
00059 #ifdef HAVE_RDTSC
00060 dest->cycles += src->cycles;
00061 #endif
00062 dest->cpu.tms_utime += src->cpu.tms_utime;
00063 dest->cpu.tms_stime += src->cpu.tms_stime;
00064 dest->cpu.tms_cutime += src->cpu.tms_cutime;
00065 dest->cpu.tms_cstime += src->cpu.tms_cstime;
00066 }
00067
00068 void timestamp_sub(struct timestamp *dest, const struct timestamp *src)
00069 {
00070 dest->micros -= src->micros;
00071 #ifdef HAVE_RDTSC
00072 dest->cycles -= src->cycles;
00073 #endif
00074 dest->cpu.tms_utime -= src->cpu.tms_utime;
00075 dest->cpu.tms_stime -= src->cpu.tms_stime;
00076 dest->cpu.tms_cutime -= src->cpu.tms_cutime;
00077 dest->cpu.tms_cstime -= src->cpu.tms_cstime;
00078 }
00079
00080 void timestamp_now(struct timestamp *dest)
00081 {
00082 struct timeval tv;
00083
00084
00085 #ifdef HAVE_RDTSC
00086 RDTSC(dest->cycles);
00087 #endif
00088 gettimeofday(&tv, NULL);
00089 dest->micros = 1000000 * (tsc_t)tv.tv_sec + tv.tv_usec;
00090 times(&dest->cpu);
00091 }
00092
00093 void timestamp_now_rev(struct timestamp *dest)
00094 {
00095 struct timeval tv;
00096
00097
00098 times(&dest->cpu);
00099 gettimeofday(&tv, NULL);
00100 dest->micros = 1000000 * (tsc_t)tv.tv_sec + tv.tv_usec;
00101 #ifdef HAVE_RDTSC
00102 RDTSC(dest->cycles);
00103 #endif
00104 }
00105
00106
00107
00108 void stopwatch_init(struct stopwatch *timer)
00109 {
00110 timestamp_init(&timer->total);
00111 timestamp_init(&timer->start);
00112 }
00113
00114 void stopwatch_start(struct stopwatch *timer)
00115 {
00116 DEBUG_WARN_MSG_IF(STOPWATCH_ACTIVE(timer),
00117 "Restarting active stopwatch.");
00118
00119 timestamp_now_rev(&timer->start);
00120 }
00121
00122 void stopwatch_stop(struct stopwatch *timer, const struct timestamp *now)
00123 {
00124 if (likely(STOPWATCH_ACTIVE(timer))) {
00125 timestamp_add(&timer->total, now);
00126 timestamp_sub(&timer->total, &timer->start);
00127 timestamp_init(&timer->start);
00128 } else {
00129 DEBUG_ONLY(NONFATAL("Stopping inactive stopwatch."));
00130 }
00131 }