Skip to content

Commit

Permalink
Cache mach timebase conversion factor
Browse files Browse the repository at this point in the history
Signed-off-by: Olivier Dormond <[email protected]>
  • Loading branch information
odormond committed Nov 4, 2021
1 parent f168f77 commit a71fedb
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
13 changes: 13 additions & 0 deletions psutil/_psutil_common.c
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,15 @@ convert_kvm_err(const char *syscall, char *errbuf) {
}
#endif

// ====================================================================
// --- macOS
// ====================================================================

#ifdef PSUTIL_OSX
#include <mach/mach_time.h>

struct mach_timebase_info MACH_TIMEBASE_INFO;
#endif

// ====================================================================
// --- Windows
Expand Down Expand Up @@ -405,5 +414,9 @@ psutil_setup(void) {
InitializeCriticalSection(&PSUTIL_CRITICAL_SECTION);
#endif

#ifdef PSUTIL_OSX
mach_timebase_info(&MACH_TIMEBASE_INFO);
#endif

return 0;
}
10 changes: 10 additions & 0 deletions psutil/_psutil_common.h
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ int psutil_setup(void);

void convert_kvm_err(const char *syscall, char *errbuf);

// ====================================================================
// --- macOS
// ====================================================================

#ifdef PSUTIL_OSX
#include <mach/mach_time.h>

extern struct mach_timebase_info MACH_TIMEBASE_INFO;
#endif

// ====================================================================
// --- Windows
// ====================================================================
Expand Down
11 changes: 4 additions & 7 deletions psutil/_psutil_osx.c
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
#include <pwd.h>
#include <unistd.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <mach/mach_vm.h>
#include <mach/shared_region.h>

Expand Down Expand Up @@ -280,19 +279,17 @@ static PyObject *
psutil_proc_pidtaskinfo_oneshot(PyObject *self, PyObject *args) {
pid_t pid;
struct proc_taskinfo pti;
struct mach_timebase_info info;
uint64_t total_user, total_system;

if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti)) <= 0)
return NULL;

mach_timebase_info(&info);
total_user = pti.pti_total_user * info.numer;
total_user /= info.denom;
total_system = pti.pti_total_system * info.numer;
total_system /= info.denom;
total_user = pti.pti_total_user * MACH_TIMEBASE_INFO.numer;
total_user /= MACH_TIMEBASE_INFO.denom;
total_system = pti.pti_total_system * MACH_TIMEBASE_INFO.numer;
total_system /= MACH_TIMEBASE_INFO.denom;

return Py_BuildValue(
"(ddKKkkkk)",
Expand Down

0 comments on commit a71fedb

Please sign in to comment.