-1

I have a process that does something and needs to be repeated after a period of 1ms. How can I set period of a process on linux ?

I am using linux 3.2.0-4-rt-amd64 (with RT-Preempt patch) on Intel i7 -2600 CPU (total 8 cores) @ 3.40 Ghz. Basically I have about 6 threads in while loop shown in code and I want threads to be executed at every 1 ms. At the end I want to measure latency of each thread.

So How to set the period 1ms ?

for example in following code, how can I repeat Task1 after every 1ms ?

while(1){

   //Task1(having threads)

}

Thank you.

HKK
  • 3
  • 1
  • 7

2 Answers2

0

Read time(7).

One millisecond is really a small period of time. (Can't you bear with e.g. a ten milliseconds delay?). I'm not sure regular processes on regular Linux on common laptop hardware are able to deal reliably with such a small period. Maybe you need RTLinux or at least real time scheduling (see sched_setscheduler(2) and this question) and perhaps a specially configured recent 3.x kernel

You can't be sure that your processing (inside your loop) is smaller than a millisecond.

You should explain what is your application doing, and what happens inside the loop.

You might have some event loop, consider using ppoll(2), timer_create(2) (see also timer_getoverrun(2)...) and/or timerfd_create(2) and clock_nanosleep(2)

(I would try something using ppoll and timerfd_create but I would accept some millisecond ticks to be skipped)

You should tell us more about your hardware and your kernel. I'm not even sure my desktop i3770K processor, asus P8Z77V motherboard, (3.13.3 PREEMPT Linux kernel) is able to reliably deal with a single millisecond delay.

(Of course, a plain loop simply calling clock_nanosleep, or better yet, using timerfd_create with ppoll, will usually do the job. But that is not reliable...)

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • The above answer is still relevant for your updated question. And you should still explain why you want a one millisecond period. What exactly is your application doing? What is happening *inside* the loop (in addition of the millisecond wait)? – Basile Starynkevitch Feb 20 '14 at 08:53
0

A call to usleep(1000) inside the while loop will do the job, i.e.:

while (1) {
    // Task1
    usleep(1000); // 1000 microseconds = 1 millisecond
}

EDIT

Since usleep() is already deprecated in favor of nanosleep(), let's use the latter instead:

struct timespec timer;
timer.tv_sec = 0;
timer.tv_nsec = 1000000L;

while (1) {
    // Task1
    nanosleep(&timer, NULL);
}
asamarin
  • 1,544
  • 11
  • 15
  • It probably won't be reliable enough. And `usleep` is obsolete and removed from Posix 2008. – Basile Starynkevitch Feb 19 '14 at 17:30
  • @BasileStarynkevitch You're right about the deprecation, sir. `nanosleep()` should be used instead. About the reliability, I guess it depends on how precise does the author need it to be. – asamarin Feb 19 '14 at 17:33