progs/rspit.c: Higher resolution timing.
authorMark Wooding <mdw@distorted.org.uk>
Mon, 22 Dec 2014 20:32:58 +0000 (20:32 +0000)
committerMark Wooding <mdw@distorted.org.uk>
Sun, 22 Mar 2015 01:02:46 +0000 (01:02 +0000)
Use double-precision for representing time, as seconds since some
arbitrary epoch.  If we're strictly portable then time(3) is all we
have, and we have to convert with difftime(3); otherwise we can have
gettimeofday(2) and convert by hand.

progs/rspit.c

index 1fb33a9..6dd36d6 100644 (file)
@@ -40,6 +40,7 @@
 
 #ifndef PORTABLE
 #  include <unistd.h>
+#  include <sys/time.h>
 #endif
 
 #include <mLib/darray.h>
@@ -1124,6 +1125,22 @@ static int genmaurer(const void *buf, size_t sz, void *p)
   return (0);
 }
 
+static double doubletime(void)
+{
+#ifdef PORTABLE
+  static time_t start = (time_t)-1;
+  time_t now = time(0);
+
+  if (start == (time_t)-1) start = now;
+  return difftime(now, start);
+#else
+  struct timeval tv;
+
+  gettimeofday(&tv, 0);
+  return (tv.tv_sec + tv.tv_usec/1000000.0);
+#endif
+}
+
 static int generate(grand *r, mp *outsz,
                    int (*func)(const void *buf, size_t sz, void *p),
                    void *p)
@@ -1133,7 +1150,7 @@ static int generate(grand *r, mp *outsz,
   unsigned percent = 0;
   mp *kb = MP_ZERO, *t = MP_NEW;
   dstr d = DSTR_INIT;
-  time_t last;
+  double now, last;
   static char baton[] = "-\\|/";
   char *bp;
   int rc;
@@ -1141,7 +1158,7 @@ static int generate(grand *r, mp *outsz,
 
   /* --- Spit out random data --- */
 
-  last = time(0);
+  last = doubletime();
   bp = baton;
   if (flags & f_progress) {
     char *errbuf = xmalloc(BUFSIZ);
@@ -1184,14 +1201,15 @@ static int generate(grand *r, mp *outsz,
     /* --- Update the display --- */
 
     if (flags & f_progress) {
-      time_t now = time(0);
       unsigned up = 0;
 
+      now = doubletime();
+
       if (percent > 100)
        up = 1;
 
       if (!outsz) {
-       if (difftime(now, last) > 1.0) {
+       if (now - last > 1.0) {
          up = 1;
        }
        if (up)
@@ -1203,7 +1221,7 @@ static int generate(grand *r, mp *outsz,
        mp_div(&t, 0, t, outsz);
        assert(!MP_NEGP(t) && MP_CMP(t, <, MP_UINT_MAX));
        pc = mp_touint(t);
-       if (pc > percent || percent > 100 || difftime(now, last) > 1.0) {
+       if (pc > percent || percent > 100 || now - last > 1.0) {
          if (percent > 100)
            percent = 0;
          percent &= ~1;