4
$\begingroup$

Most programming languages such as Python and C++ but only after 2011 have some way of initiating a time delay for a fixed amount of real time. C lacks any of such facilities and C++ lacked them until 2011 which is relatively recently considering C++ was from the 80s.

Is there more to adding timing capabilities them that one would first expect? What are the limitations that prevents some languages from adding them? I would expect any architecture to have the capability to access a real-time clock, so what does one give up by mandating support for timing functions?

$\endgroup$
1
  • 2
    $\begingroup$ C does have sleep but only in platform specific headers. It functions basically the same on every platform though so it seems the only reason it wasn't standardizes is that nobody standardized it when the standard library was defined. (Now answering since I am unsure) $\endgroup$
    – mousetail
    Commented Jul 1, 2023 at 18:48

3 Answers 3

5
$\begingroup$

Sleeping prototypically blocks a thread, which isn’t always preferable. Swift (and no other language that I’m aware of) circumvents this by making its sleep function async. It schedules the rest of the task to be completed after that much time, and throws a CancellationError if the task is cancelled before that happens.

$\endgroup$
5
$\begingroup$

Portability is one problem. Different systems might:

  • Support different timing precisions (seconds, milliseconds, microseconds, nanoseconds, etc.)
  • Have different behavior regarding interrupts (e.g., sleep can be interrupted on POSIX due to things other than the specified time being reached, necessitating sleeping again)
  • Differ on whether sleeping for zero seconds is allowed, and how that behaves

With some work one could hide most of these differences from the caller, but this does necessitate some extra work, and any inconsistencies that can't be fixed (e.g., nanosecond precision support) would need to be documented and handled in a reasonable manner.

$\endgroup$
2
$\begingroup$

One good reason can be to not give the users a false hope that the requested delay will actually be honoured at any meaningful precision (and if we're talking about any typical OS, there is a guarantee it won't).

If the users are interested in an actual real-time delay, they must do it on their own in a platform/problem specific way, and it is not going to be easy or portable. Sad reality, but it is better respected and acknowledged.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .