Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use time_nanosleep?

Tags:

php

Just stumbled upon time_nanosleep() and started to wonder, when would you ever want to use this?

Also, is it even possible to work with such short timespans in a scripting language like PHP?

like image 973
professorsloth Avatar asked Apr 18 '12 08:04

professorsloth


1 Answers

No, it is never possible to work with single nanoseconds. Only the context switch in Linux is usually in the hundreds of nanoseconds, overhead from the Zend engine not included.

I checked the PHP source code and it is just a simple wrapper around the C nanosleep function. The man page for nanosleep says:

nanosleep() suspends the execution of the calling thread until either at least the time specified in *req has elapsed

...

Compared to sleep(3) and usleep(3), nanosleep() has the following advantages: it provides a higher resolution for specifying the sleep interval

So it's all about how small you want to specify the interval. Since usleep is specified in microseconds (thousands of nanoseconds), it's basic unit may be too large for some very small sleep intervals.

like image 76
Emil Vikström Avatar answered Oct 07 '22 10:10

Emil Vikström