[Python-ideas] Improve os.times() resolution

Giampaolo Rodola' g.rodola at gmail.com
Sun Mar 24 08:15:48 EDT 2019

It turns out we could use resource.getrusage() which provides micro
seconds (tested on Linux and macOS):

    import os, resource
    for x in range(10000000):  # warm up
    for x in range(5):
        a = os.times()
        b = resource.getrusage(resource.RUSAGE_SELF)
        print(a.user, a.system)
        print(b.ru_utime, b.ru_stime)

...it prints:

    0.39 0.01
    0.394841 0.011963999999999999
    0.39 0.01
    0.394899 0.011966
    0.39 0.01
    0.394908 0.011966
    0.39 0.01
    0.394936 0.011967
    0.39 0.01
    0.394963 0.011968

getrusage(RUSAGE_CHILDREN) can be used to calculate "children_user"
and "children_system". I see 2 possibilities here:

1) doc fix, mentioning that resource.getrusage provides a better resolution
2) if available (it should always be as it's a POSIX standard), just
use getrusage in Modules/posixmodule.c. It seems we can check
availability by reusing HAVE_SYS_RESOURCE_H and HAVE_SYS_TIME_H
definitions which are already in place.

I'm not sure what's best to do as os.* functions usually expose the
original C function with the same name, but given that "elapsed" field
is not part of times(2) struct and that on Windows "elapsed",
"children_user" and "children_system" are set to 0 it appears there
may be some space for flexibility here.


Giampaolo - http://grodola.blogspot.com

More information about the Python-ideas mailing list