clinuxusleep

Sleep less than 1ms


I am trying create cpu load generator tool. In which my input will be a number which is in between 0-100. I m using time function for calculating the load and i check the load. If load exceeds a desired value i try to sleep the process. The issue i m facing i that i get a desired load for but only for time period of 500ms or more. Not less than that. I m checking the load on a tool called as 'top'. When i try to decrease the time period in top. I observe the load fluctuations. Is there any ways to make a process sleep for 1ms or less.


Solution

  • Since you tagged this question linux-kernel, I will answer with specific details about the Linux scheduler...

    Short answer: no you can't sleep for less that 1ms, because that's the resolution of the scheduler. In other words, the kernel is waking up every millisecond to decide which process to schedule, so sleeping for less than that is not possible.

    Long answer: designing a cpu load generator for Linux was a subject complicated enough to deserve multiple publications. You can try the terms cpu burner and cpu load generator on Google Scholar to find more info. One of the most efficient way now is not to do it: there is cpu bandwith limitation in the cgroups feature of any recent kernel, meaning you don't have to execute code to limit the amount of cpu time available to other processes.

    And no, nanosleep does not provide any guaranty that your process will be stopped, only that the clock advanced at least the amount of time you requested.