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

Gregory P. Smith greg at krypto.org
Sun Mar 24 12:24:38 EDT 2019


On Sun, Mar 24, 2019 at 5:16 AM Giampaolo Rodola' <g.rodola at gmail.com>
wrote:

> 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
>         pass
>     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.
>
> Thoughts?
>

I'd just document that resource.getrusage() provides better data.  That is
what man pages for times(3) have done as well.  It is good to keep the os
module close to the underlying library/system calls and leave it to higher
level code to abstract and choose as deemed appropriate.

-gps
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190324/498ca50b/attachment.html>


More information about the Python-ideas mailing list