1 /*
2 +----------------------------------------------------------------------+
3 | Copyright (c) The PHP Group |
4 +----------------------------------------------------------------------+
5 | This source file is subject to version 3.01 of the PHP license, |
6 | that is bundled with this package in the file LICENSE, and is |
7 | available through the world-wide-web at the following url: |
8 | http://www.php.net/license/3_01.txt |
9 | If you did not receive a copy of the PHP license and are unable to |
10 | obtain it through the world-wide-web, please send a note to |
11 | license@php.net so we can mail you a copy immediately. |
12 +----------------------------------------------------------------------+
13 | Authors: Kalle Sommer Nielsen <kalle@php.net> |
14 +----------------------------------------------------------------------+
15 */
16
17 #include <php.h>
18 #include <psapi.h>
19 #include "getrusage.h"
20
21 /*
22 * Parts of this file is based on code from the OpenVSwitch project, that
23 * is released under the Apache 2.0 license and is copyright 2014 Nicira, Inc.
24 * and have been modified to work with PHP.
25 */
26
usage_to_timeval(FILETIME * ft,struct timeval * tv)27 static zend_always_inline void usage_to_timeval(FILETIME *ft, struct timeval *tv)
28 {
29 ULARGE_INTEGER time;
30
31 time.LowPart = ft->dwLowDateTime;
32 time.HighPart = ft->dwHighDateTime;
33
34 tv->tv_sec = (zend_long) (time.QuadPart / 10000000);
35 tv->tv_usec = (zend_long) ((time.QuadPart % 10000000) / 10);
36 }
37
getrusage(int who,struct rusage * usage)38 PHPAPI int getrusage(int who, struct rusage *usage)
39 {
40 FILETIME ctime, etime, stime, utime;
41
42 memset(usage, 0, sizeof(struct rusage));
43
44 if (who == RUSAGE_SELF) {
45 PROCESS_MEMORY_COUNTERS pmc;
46 HANDLE proc = GetCurrentProcess();
47
48 if (!GetProcessTimes(proc, &ctime, &etime, &stime, &utime)) {
49 return -1;
50 } else if(!GetProcessMemoryInfo(proc, &pmc, sizeof(pmc))) {
51 return -1;
52 }
53
54 usage_to_timeval(&stime, &usage->ru_stime);
55 usage_to_timeval(&utime, &usage->ru_utime);
56
57 usage->ru_majflt = pmc.PageFaultCount;
58 usage->ru_maxrss = pmc.PeakWorkingSetSize / 1024;
59
60 return 0;
61 } else if (who == RUSAGE_THREAD) {
62 if (!GetThreadTimes(GetCurrentThread(), &ctime, &etime, &stime, &utime)) {
63 return -1;
64 }
65
66 usage_to_timeval(&stime, &usage->ru_stime);
67 usage_to_timeval(&utime, &usage->ru_utime);
68
69 return 0;
70 } else {
71 return -1;
72 }
73 }
74