getrusage.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. | https://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. #include <php.h>
  17. #include <psapi.h>
  18. #include "getrusage.h"
  19. /*
  20. * Parts of this file is based on code from the OpenVSwitch project, that
  21. * is released under the Apache 2.0 license and is copyright 2014 Nicira, Inc.
  22. * and have been modified to work with PHP.
  23. */
  24. static zend_always_inline void usage_to_timeval(FILETIME *ft, struct timeval *tv)
  25. {
  26. ULARGE_INTEGER time;
  27. time.LowPart = ft->dwLowDateTime;
  28. time.HighPart = ft->dwHighDateTime;
  29. tv->tv_sec = (zend_long) (time.QuadPart / 10000000);
  30. tv->tv_usec = (zend_long) ((time.QuadPart % 10000000) / 10);
  31. }
  32. PHPAPI int getrusage(int who, struct rusage *usage)
  33. {
  34. FILETIME ctime, etime, stime, utime;
  35. memset(usage, 0, sizeof(struct rusage));
  36. if (who == RUSAGE_SELF) {
  37. PROCESS_MEMORY_COUNTERS pmc;
  38. HANDLE proc = GetCurrentProcess();
  39. if (!GetProcessTimes(proc, &ctime, &etime, &stime, &utime)) {
  40. return -1;
  41. } else if(!GetProcessMemoryInfo(proc, &pmc, sizeof(pmc))) {
  42. return -1;
  43. }
  44. usage_to_timeval(&stime, &usage->ru_stime);
  45. usage_to_timeval(&utime, &usage->ru_utime);
  46. usage->ru_majflt = pmc.PageFaultCount;
  47. usage->ru_maxrss = pmc.PeakWorkingSetSize / 1024;
  48. return 0;
  49. } else if (who == RUSAGE_THREAD) {
  50. if (!GetThreadTimes(GetCurrentThread(), &ctime, &etime, &stime, &utime)) {
  51. return -1;
  52. }
  53. usage_to_timeval(&stime, &usage->ru_stime);
  54. usage_to_timeval(&utime, &usage->ru_utime);
  55. return 0;
  56. } else {
  57. return -1;
  58. }
  59. }