Have a slightly more efficient event loop.
authorPierre Habouzit <madcoder@debian.org>
Sat, 10 Nov 2007 14:14:47 +0000 (15:14 +0100)
committerPierre Habouzit <madcoder@debian.org>
Sat, 10 Nov 2007 14:14:47 +0000 (15:14 +0100)
Signed-off-by: Pierre Habouzit <madcoder@debian.org>
demo/boxshell.c

index fa7d2ee..76af914 100644 (file)
@@ -21,6 +21,7 @@
 static int getout = 0, sigwinch = 0;
 static int screen_w, screen_h;
 static WINDOW *term_win;
 static int getout = 0, sigwinch = 0;
 static int screen_w, screen_h;
 static WINDOW *term_win;
+static struct timeval const slice = { 0, 1000 * 1000 / 100 };
 
 void handler(int signo)
 {
 
 void handler(int signo)
 {
@@ -34,10 +35,29 @@ void handler(int signo)
     }
 }
 
     }
 }
 
+static struct timeval timeval_add(struct timeval a, struct timeval b)
+{
+    int usec = a.tv_usec + b.tv_usec;
+    a.tv_sec += b.tv_sec;
+    while (usec > 1000 * 1000) {
+        a.tv_sec += 1;
+        usec -= 1000 * 1000;
+    }
+    a.tv_usec = usec;
+    return a;
+}
+
+static int is_expired(struct timeval now, struct timeval expiry)
+{
+    return now.tv_sec > expiry.tv_sec
+        || (now.tv_sec == expiry.tv_sec && now.tv_usec > expiry.tv_usec);
+}
+
 int main(void)
 {
     madtty_t *rt;
     int dirty = 0;
 int main(void)
 {
     madtty_t *rt;
     int dirty = 0;
+    struct timeval next;
 
     signal(SIGCHLD, handler);
     signal(SIGWINCH, handler);
 
     signal(SIGCHLD, handler);
     signal(SIGWINCH, handler);
@@ -57,9 +77,10 @@ int main(void)
 
     /* keep reading keypresses from the user and passing them to the terminal;
      * also, redraw the terminal to the window at each iteration */
 
     /* keep reading keypresses from the user and passing them to the terminal;
      * also, redraw the terminal to the window at each iteration */
+    gettimeofday(&next, NULL);
     while (!getout) {
     while (!getout) {
+        struct timeval tv = { 0, 1000 * 1000 / 100 };
         fd_set rfds;
         fd_set rfds;
-        struct timeval tv = { 0, 1000 * 1000 / 50 };
         int ch;
 
         FD_ZERO(&rfds);
         int ch;
 
         FD_ZERO(&rfds);
@@ -103,10 +124,12 @@ int main(void)
             dirty = 1;
         }
 
             dirty = 1;
         }
 
-        if (dirty) {
+        gettimeofday(&tv, NULL);
+        if (dirty && is_expired(tv, next)) {
             madtty_draw(rt, term_win, 0, 0);
             wrefresh(term_win);
             dirty = 0;
             madtty_draw(rt, term_win, 0, 0);
             wrefresh(term_win);
             dirty = 0;
+            next = timeval_add(tv, slice);
         }
     }
 
         }
     }