getrusage.c 2.6 KB

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