[Python-ideas] Add time.time_ns(): system clock with nanosecond resolution

Victor Stinner victor.stinner at gmail.com
Mon Oct 16 12:49:18 EDT 2017

2017-10-16 18:13 GMT+02:00 Todd <toddrjen at gmail.com>:
> I am not suggesting implementing a new numeric data type.  People wouldn't
> use the class directly like they would an int or float, they would simply
> use it to define the the precision and numeric type (float, int, decimal).
> Then they would have access to the entire "time" API as methods.  So for
> example you could do something like:

I tried to include your idea in a more general description of "different API":

>    >>> import time
>    >>>
>    >>> ns_time_int = time.time_base(units='ns', type=int)
>    >>> ms_time_dec = time.time_base(units=1e-6, type='Decimal')
>    >>> s_time_float= time.time_base(units=1, type=float)  # This is
> identical to the existing "time" functions
>    >>>
>    >>> ns_time_int.clock()
>    4978480000
>    >>> ms_time_dec.clock()
>    Decimal('5174165.999999999')
>    >>> s_time_float.clock()
>    5.276855

*I* dislike this API. IMHO it's overcomplicated just to get the
current time :-( For example, I wouldn't like to have to teach to a
newbie "how to get the current time" with such API.

I also expect that the implementation will be quite complicated.
Somewhere, you will need an internal "standard" type to store time, a
"master type" used to build all other types. Without that, you would
have to duplicate code and it would be a mess. You have many options
for such master time.

For the private C API of CPython, I already "implemented" such "master
type": I decided to use C int64_t type: it's a 64-bit signed integer.
There is an API on top of it which is unit agnostic, while it uses
nanoseconds in practice. The private "pytime" API supports many
timestamps conversions to adapt to all funny operating system

* from seconds: C int
* from nanoseconds: C long long
* from seconds: Python float or int
* from milliseconds: Python float or int
* to seconds: C double
* to milliseconds: _PyTime_t
* to microseconds: _PyTime_t
* to nanoseconds: Python int
* to timeval (struct timeval)
* to timeval (time_t seconds, int us)
* to timespec (struct timespec)

At the end, I think that it's better to only provide the "master type"
at the Python level, so nanoseconds as Python int. You can *easily*
implement your API on top of the PEP 564. You will be limited to
nanosecond resolution, but in practice, all clocks are already limited
to this resolution through operating system APIs:


More information about the Python-ideas mailing list