0

How to call a method/function 50 time in a second then calculate time spent, If time spent is less than one second then sleep for (1-timespent) seconds.

Below is the pseudo code

while(1)
{
  start_time = //find current time
  int msg_count=0;
  send_msg();
  msg_count++;

  // Check time after sending 50 messages
  if(msg_count%50 == 0)
  {
   curr_time = //Find current time
   int timeSpent = curr_time - start_time ;
   int waitingTime;

   start_time = curr_time ;

   waitingTime = if(start_time < 1 sec) ? (1 sec - timeSpent) : 0;
   wait for waitingTime; 
  }
}

I am new with Timer APIs. Can anyone help me that what are the timer APIs, I have to use to achieve this. I want portable code.

harpun
  • 4,022
  • 1
  • 36
  • 40
  • How precise do you want to be? Are you sure that your processing (`send_msg` notably, which perhaps might block) is always taking much less than 20 milliseconds, i.e. the period for 50Hz ? – Basile Starynkevitch Oct 12 '13 at 06:40
  • 1
    possible duplicate of [C++ Timer function to provide time in nano seconds](http://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds) – Joe Oct 12 '13 at 06:48

1 Answers1

2

First, read the time(7) man page.

Then you may want to call timer_create(2) to set up a timer. To query about time, use clock_gettime(2)

You probably may want to wait and multiplex on some input and output. poll(2) is useful for this. To sleep for a small amount of time without using the CPU consider nanosleep(2)

If using timer doing signals, read signal(7) and be careful because signal handlers are restricted to async-signal-safe functions (consider having a signal handler which just sets some global volatile sig_atomic_t flag). You may also be interested by the Linux specific timerfd_create(2) (which you could poll or pass to your event loop).

You might want to use some existing event loop library, like libevent or libev (or those from GTK/Glib, Qt, etc...), which are often using poll (or fancier things). The linux specific eventfd(2) and signalfd(2) might be very helpful.

Advanced Linux Programming is also useful to read.

If send_msg is doing network I/O, you probably need to redesign your program around some event loop (perhaps your own, based on poll) - you'll need to multiplex (i.e. poll) both on network sends and network recieves. continuation-passing style is then a useful paradigm.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547