Browse Source

Remove functions timeSleep and timeSleepUntil, add timeShift

Olivier Marty 9 years ago
parent
commit
9383a94991
3 changed files with 22 additions and 28 deletions
  1. 2 1
      main.c
  2. 18 21
      time.c
  3. 2 6
      time.h

+ 2 - 1
main.c

@@ -139,7 +139,8 @@ int main(int argc, char **argv)
     richTextFree(rt);
   }
   printf("0 !\n");
-  timeInitialize(-factor*shift);
+  timeInitialize();
+  timeShift(-factor*shift);
   
   int id = 0;
   t_events events = eventsInit(8);

+ 18 - 21
time.c

@@ -20,17 +20,19 @@
 #include <errno.h>
 #include <stdlib.h>
 
-int timeSleep(struct timespec t)
+void normalize(struct timespec *t)
 {
-  int r = -2;
-  if(t.tv_sec >= 0)
+  // TODO compute directly ?
+  while(t->tv_nsec < 0)
   {
-    do
-    {
-      r = nanosleep(&t, &t);
-    } while(errno == EINTR);
+    t->tv_nsec += 1000000000;
+    t->tv_sec -= 1;
+  }
+  while(t->tv_nsec >= 1000000000)
+  {
+    t->tv_nsec -= 1000000000;
+    t->tv_sec += 1;
   }
-  return r;
 }
 
 struct timespec timeDiff(struct timespec a, struct timespec b)
@@ -38,11 +40,7 @@ struct timespec timeDiff(struct timespec a, struct timespec b)
   struct timespec r;
   r.tv_sec = a.tv_sec - b.tv_sec;
   r.tv_nsec = a.tv_nsec - b.tv_nsec;
-  if(r.tv_nsec < 0)
-  {
-    r.tv_nsec += 1000000000;
-    r.tv_sec -= 1;
-  }
+  normalize(&r);
   return r;
 }
 
@@ -66,7 +64,7 @@ struct timespec timeFactor(struct timespec a, double f)
 struct timespec begin;
 struct timespec tPause; // beginning of the pause
 int pause;
-void timeInitialize(int rel)
+void timeInitialize()
 {
   pause = 0;
   if(clock_gettime(CLOCK_REALTIME, &begin) < 0)
@@ -74,7 +72,12 @@ void timeInitialize(int rel)
     perror("clock_gettime()");
     exit(1);
   }
-  begin.tv_sec += rel;
+}
+
+void timeShift(double rel)
+{
+  begin.tv_nsec += rel*1000000000.;
+  normalize(&begin);
 }
 
 struct timespec timeGetRelative()
@@ -91,12 +94,6 @@ struct timespec timeGetRelative()
   return timeDiff(r, begin);
 }
 
-int timeSleepUntil(struct timespec t)
-{
-  struct timespec current = timeGetRelative();
-  return timeSleep(timeDiff(t, current));
-}
-
 struct timespec timeCreate(time_t s, long ns)
 {
   struct timespec r;

+ 2 - 6
time.h

@@ -23,16 +23,13 @@
 
 typedef struct timespec mytime;
 
-void timeInitialize(int rel); // add rel seconds to the clock
+void timeInitialize(); // start the clock
+void timeShift(double rel); // arr rel seconde to the clock
 mytime timeGetRelative();
-// return -2 if t is in the past
-int timeSleepUntil(mytime t);
 int timeInFuture(mytime t);
 
 mytime timeCreate(time_t s, long ns);
 
-// return -2 if t is negative
-int timeSleep(mytime t);
 mytime timeDiff(mytime a, mytime b);
 // f should be >= 0
 // this function was wrong, now it returns a
@@ -42,4 +39,3 @@ void timePause(int pause); // pause and resume the clock
 int timeIsPaused();
 
 #endif
-