RuntimeProcessUtils.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. namespace TriLibCore.Samples
  5. {
  6. public class RuntimeProcessUtils
  7. {
  8. #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
  9. [DllImport("psapi.dll", SetLastError = true)]
  10. private static extern bool GetProcessMemoryInfo(IntPtr hProcess, out PROCESS_MEMORY_COUNTERS counters, int size);
  11. [StructLayout(LayoutKind.Sequential, Size = 72)]
  12. private struct PROCESS_MEMORY_COUNTERS
  13. {
  14. public uint cb;
  15. public uint PageFaultCount;
  16. public UInt64 PeakWorkingSetSize;
  17. public UInt64 WorkingSetSize;
  18. public UInt64 QuotaPeakPagedPoolUsage;
  19. public UInt64 QuotaPagedPoolUsage;
  20. public UInt64 QuotaPeakNonPagedPoolUsage;
  21. public UInt64 QuotaNonPagedPoolUsage;
  22. public UInt64 PagefileUsage;
  23. public UInt64 PeakPagefileUsage;
  24. }
  25. public static long GetProcessMemory()
  26. {
  27. if (GetProcessMemoryInfo(Process.GetCurrentProcess().Handle, out var processMemoryCounters, Marshal.SizeOf<PROCESS_MEMORY_COUNTERS>()))
  28. {
  29. var memoryUsage = processMemoryCounters.WorkingSetSize;
  30. return (long)memoryUsage;
  31. }
  32. return 0;
  33. }
  34. #else
  35. public static long GetProcessMemory()
  36. {
  37. return 0;
  38. }
  39. #endif
  40. }
  41. }