Author vstinner
Recipients belopolsky, loewis, vstinner
Date 2012-01-26.21:00:34
SpamBayes Score 1.11022e-16
Marked as misclassified No
Message-id <>
Attached patch adds an optional format argument to time.time(), time.clock(), time.wallclock(), time.clock_gettime() and time.clock_getres() to get the timestamp as a different format. By default, the float type is still used, but it will be possible to pass "format" to get the timestamp as a decimal.Decimal object.

Some advantages of using decimal.Decimal instead of float:
 - no loss of precision during conversion from base 2 to base 10 (converting the float to a string)
 - the resolution of the clock is stored in the Decimal object
 - for big number, Decimal doesn't loose precision

Using Decimal is also motivated by the fact than Python 3.3 has now access to clock having a resolution of 1 nanosecond: clock_gettime(CLOCK_REALTIME). Well, it doesn't mean that the clock is accurate, but Python should not loose precision just because it uses floatting point instead of integers.

About the API: I chose to add a string argument to allow maybe later to support user defined formats, or at least add new builtin formats. For example, someone proposed 128 bits float in the issue #11457.


The internal format is:

typedef struct {
    time_t seconds;
    /* floatpart can be zero */
    size_t floatpart;
    /* divisor cannot be zero */
    size_t divisor;
    /* log10 of the clock resoltion, the real resolution is 10^resolution,
       resolution is in range [-9; 0] */
    int resolution;
} _PyTime_t;

I don't know if size_t is big enough to store any "floatpart" value: time.clock() uses a LARGE_INTEGER internally. I tested my patch on Linux 32 and 64 bits, but not yet on Windows.

The internal function encoding a timestamp to Decimal caches the resolution objects (10^resolution, common clock resolutions: 10^-6, 10^-9) in a dict, and a Context object.

I computed that 22 decimal digits should be enough to compute a timestamp of 10,000 years. Extract of my patch:

"Use 12 decimal digits to store 10,000 years in seconds + 9 decimal digits for the floating part in nanoseconds + 1 decimal digit to round correctly"

>>> str(int(3600*24*365.25*10000))
>>> len(str(int(3600*24*365.25*10000)))


See also the issue #11457 which is linked to this topic, but not exactly the same because it concerns a low level function (os.stat()).
Date User Action Args
2012-01-26 21:00:40vstinnersetrecipients: + vstinner, loewis, belopolsky
2012-01-26 21:00:37vstinnersetmessageid: <>
2012-01-26 21:00:37vstinnerlinkissue13882 messages
2012-01-26 21:00:36vstinnercreate