]> git.armaanb.net Git - pong.git/commitdiff
Sleep during loops
authorArmaan Bhojwani <me@armaanb.net>
Sun, 16 May 2021 02:34:30 +0000 (22:34 -0400)
committerArmaan Bhojwani <me@armaanb.net>
Sun, 16 May 2021 02:34:30 +0000 (22:34 -0400)
Doesn't max out the CPU

pong.c

diff --git a/pong.c b/pong.c
index 0a750506c13d8a6db893ebfebf8503874781a306..c15860731b9cabf998e285cb39223741450781d2 100644 (file)
--- a/pong.c
+++ b/pong.c
@@ -3,6 +3,7 @@
 #include <stdio.h>
 #include <unistd.h>
 #include <sys/time.h>
+#include <sys/select.h>
 #include <time.h>
 #include <math.h>
 
@@ -35,6 +36,14 @@ randsign(void)
        return pow(-1, rand());
 }
 
+void
+msleep(void)
+{
+       struct timeval timeout;
+       timeout.tv_usec = 10000;
+       select(NULL, NULL, NULL, NULL, &timeout); // Sleep 100 ms
+}
+
 int
 main(void) {
        srand((unsigned int)time(NULL));
@@ -95,6 +104,7 @@ main(void) {
                                } else if (key == 'q') {
                                        die(0);
                                }
+                               msleep();
                        }
                }
 
@@ -177,5 +187,6 @@ main(void) {
                        mvprintw(y, x, " ");
                        y = (y == max_y) ? max_y - 1 : 1;
                }
+               msleep();
        }
 }