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

Giampaolo Rodola' g.rodola at gmail.com
Sun Mar 24 17:19:53 EDT 2019


On Sun, Mar 24, 2019 at 2:29 PM Anders Hovmöller <boxed at killingar.net> wrote:
>
> Have you checked how much overhead the two functions have? That seems like an obvious way this proposal could go south.

Without patch:

    $ ./python -m timeit -s "import os" "os.times()"
    500000 loops, best of 5: 546 nsec per loop

With patch:

    $ ./python -m timeit -s "import os" "os.times()"
    200000 loops, best of 5: 1.23 usec per loop

The patch:

    diff --git a/Modules/posixmodule.c b/Modules/posixmodule.c
    index 3f76018357..ad91ed702a 100644
    --- a/Modules/posixmodule.c
    +++ b/Modules/posixmodule.c
    @@ -8035,6 +8035,14 @@ os_times_impl(PyObject *module)
     #else /* MS_WINDOWS */
     {

    +#if defined(HAVE_SYS_RESOURCE_H)
    +    struct rusage ruself;
    +    struct rusage ruchildren;
    +    if (getrusage(RUSAGE_SELF, &ruself) == -1)
    +        return posix_error();
    +    if (getrusage(RUSAGE_CHILDREN, &ruchildren) == -1)
    +        return posix_error();
    +#endif

         struct tms t;
         clock_t c;
    @@ -8043,10 +8051,18 @@ os_times_impl(PyObject *module)
         if (c == (clock_t) -1)
             return posix_error();
         return build_times_result(
    +
    +#if defined(HAVE_SYS_RESOURCE_H)
    +                         doubletime(ruself.ru_utime),
    +                         doubletime(ruself.ru_stime),
    +                         doubletime(ruchildren.ru_utime),
    +                         doubletime(ruchildren.ru_stime),
    +#else
                              (double)t.tms_utime / ticks_per_second,
                              (double)t.tms_stime / ticks_per_second,
                              (double)t.tms_cutime / ticks_per_second,
                              (double)t.tms_cstime / ticks_per_second,
    +#endif
                              (double)c / ticks_per_second);
     }
     #endif /* MS_WINDOWS */

-- 
Giampaolo - http://grodola.blogspot.com


More information about the Python-ideas mailing list