当前位置:   article > 正文

.NET 中 GetProcess 相关方法的性能

getprocessesbyname 性能

 

.NET 的 Process 类中提供了查找进程的若干方法,其中部分方法还比较消耗性能。如果你试图优化查找进程相关方法的性能,可能本文分享的一些耗时数据可以作为参考。


 

性能比较

Process 类中提供了四种查询进程的方法:

  • GetProcesses
    • 获取当前计算机或远程计算机上运行的所有进程。
  • GetProcessById
    • 获取当前计算机或远程计算机上 pid 为 指定值的进程。
  • GetProcessesByName
    • 根据进程的名字查找当前计算机或远程计算机上的进程。
  • GetCurrentProcess
    • 获取当前进程的 Process 实例。

先给出我的实测数据(100 次执行耗时):

  • Process.GetProcesses()
    • 00:00:00.7254688
  • Process.GetProcessById(id)
    • 00:00:01.3660640(实际数值取决于当前进程数)
  • Process.GetProcessesByName("Walterlv.Demo")
    • 00:00:00.5604279
  • Process.GetCurrentProcess()
    • 00:00:00.0000546

结果显示获取所有进程实例的 GetProcesses 方法速度竟然比获取单个进程实例的 GetProcessById 还要快得多!额外地,根据名称查找进程比前两者都快,获取当前进程实例的方法快得不是一个数量级。

这些速度差异源于哪里

我们先看看最慢的方法 GetProcessIds,它的最本质的实现在 ProcessManager 类中:

  1. // ProcessManager
  2. public static int[] GetProcessIds() {
  3. int[] processIds = new int[256];
  4. int size;
  5. for (;;) {
  6. if (!NativeMethods.EnumProcesses(processIds, processIds.Length * 4, out size))
  7. throw new Win32Exception();
  8. if (size == processIds.Length * 4) {
  9. processIds = new int[processIds.Length * 2];
  10. continue;
  11. }
  12. break;
  13. }
  14. int[] ids = new int[size / 4];
  15. Array.Copy(processIds, ids, ids.Length);
  16. return ids;
  17. }

先创建一个 256 长度的数组,然后使用本机函数枚举进程列表填充这个数组。如果实际所需的数组大小与传入的数组大小相等,说明数组用完了,有可能进程数比 256 个多。所以,将数组长度扩大为两倍,随后再试一次。直到发现申请的数组长度足够存下进程数为止。

这里用到了本机方法 EnumProcesses 来枚举进程。传入的 size 要乘以 4 是因为传入的是字节数,一个 int 是 4 个字节。

  1. // NativeMethods
  2. [DllImport("psapi.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
  3. public static extern bool EnumProcesses(int[] processIds, int size, out int needed);

所以我们可以得知,如果当前计算机中的进程数小于 256 个,那么枚举进程方法仅需执行一次;而如果大于或等于 256 个,则枚举进程的方法需要执行两次或更多次,这是性能很差的一个重要原因。

另外,GetProcesses 方法就要复杂得多,其核心调用的是 ProcessManager.GetProcessInfos 方法。方法很长,但其大体思路是获取当前计算机上的线程列表,然后将线程所在的进程储存到哈希表中(相当于去重),随后返回此哈希表的数组副本。

  1. // ProcessManager
  2. static ProcessInfo[] GetProcessInfos(IntPtr dataPtr, Predicate<int> processIdFilter) {
  3. // 60 is a reasonable number for processes on a normal machine.
  4. Hashtable processInfos = new Hashtable(60);
  5. long totalOffset = 0;
  6. while(true) {
  7. IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset);
  8. SystemProcessInformation pi = new SystemProcessInformation();
  9. Marshal.PtrToStructure(currentPtr, pi);
  10. // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD.
  11. int processInfoProcessId = pi.UniqueProcessId.ToInt32();
  12. if (processIdFilter == null || processIdFilter(processInfoProcessId)) {
  13. // get information for a process
  14. ProcessInfo processInfo = new ProcessInfo();
  15. processInfo.processId = processInfoProcessId;
  16. processInfo.handleCount = (int)pi.HandleCount;
  17. processInfo.sessionId = (int)pi.SessionId;
  18. processInfo.poolPagedBytes = (long)pi.QuotaPagedPoolUsage;;
  19. processInfo.poolNonpagedBytes = (long)pi.QuotaNonPagedPoolUsage;
  20. processInfo.virtualBytes = (long)pi.VirtualSize;
  21. processInfo.virtualBytesPeak = (long)pi.PeakVirtualSize;
  22. processInfo.workingSetPeak = (long)pi.PeakWorkingSetSize;
  23. processInfo.workingSet = (long)pi.WorkingSetSize;
  24. processInfo.pageFileBytesPeak = (long)pi.PeakPagefileUsage;
  25. processInfo.pageFileBytes = (long)pi.PagefileUsage;
  26. processInfo.privateBytes = (long)pi.PrivatePageCount;
  27. processInfo.basePriority = pi.BasePriority;
  28. if( pi.NamePtr == IntPtr.Zero) {
  29. if( processInfo.processId == NtProcessManager.SystemProcessID) {
  30. processInfo.processName = "System";
  31. }
  32. else if( processInfo.processId == NtProcessManager.IdleProcessID) {
  33. processInfo.processName = "Idle";
  34. }
  35. else {
  36. // for normal process without name, using the process ID.
  37. processInfo.processName = processInfo.processId.ToString(CultureInfo.InvariantCulture);
  38. }
  39. }
  40. else {
  41. string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength/sizeof(char)));
  42. //
  43. // On old operating system (NT4 and windows 2000), the process name might be truncated to 15
  44. // characters. For example, aspnet_admin.exe will show up in performance counter as aspnet_admin.ex.
  45. // Process class try to return a nicer name. We used to get the main module name for a process and
  46. // use that as the process name. However normal user doesn't have access to module information,
  47. // so normal user will see an exception when we try to get a truncated process name.
  48. //
  49. if (ProcessManager.IsOSOlderThanXP && (processName.Length == 15)) {
  50. if (processName.EndsWith(".", StringComparison.OrdinalIgnoreCase)) {
  51. processName = processName.Substring(0, 14);
  52. }
  53. else if (processName.EndsWith(".e", StringComparison.OrdinalIgnoreCase)) {
  54. processName = processName.Substring(0, 13);
  55. }
  56. else if (processName.EndsWith(".ex", StringComparison.OrdinalIgnoreCase)) {
  57. processName = processName.Substring(0, 12);
  58. }
  59. }
  60. processInfo.processName = processName;
  61. }
  62. // get the threads for current process
  63. processInfos[processInfo.processId] = processInfo;
  64. currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi));
  65. int i = 0;
  66. while( i < pi.NumberOfThreads) {
  67. SystemThreadInformation ti = new SystemThreadInformation();
  68. Marshal.PtrToStructure(currentPtr, ti);
  69. ThreadInfo threadInfo = new ThreadInfo();
  70. threadInfo.processId = (int)ti.UniqueProcess;
  71. threadInfo.threadId = (int)ti.UniqueThread;
  72. threadInfo.basePriority = ti.BasePriority;
  73. threadInfo.currentPriority = ti.Priority;
  74. threadInfo.startAddress = ti.StartAddress;
  75. threadInfo.threadState = (ThreadState)ti.ThreadState;
  76. threadInfo.threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason);
  77. processInfo.threadInfoList.Add(threadInfo);
  78. currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti));
  79. i++;
  80. }
  81. }
  82. if (pi.NextEntryOffset == 0) {
  83. break;
  84. }
  85. totalOffset += pi.NextEntryOffset;
  86. }
  87. ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
  88. processInfos.Values.CopyTo(temp, 0);
  89. return temp;
  90. }

GetProcessesByName 方法就比较奇怪了,因为其本质上就是调用了 Process.GetProcesses 方法,并在其后额外执行了一些代码。理论上不应该出现耗时更短的情况。事实上,在测试中,我将 GetProcessesGetProcessesByName 方法的执行调换顺序也能得到稳定一致的结果,都是 GetProcessesByName 更快。

  1. public static Process[] GetProcessesByName(string processName, string machineName) {
  2. if (processName == null) processName = String.Empty;
  3. Process[] procs = GetProcesses(machineName);
  4. ArrayList list = new ArrayList();
  5. for(int i = 0; i < procs.Length; i++) {
  6. if( String.Equals(processName, procs[i].ProcessName, StringComparison.OrdinalIgnoreCase)) {
  7. list.Add( procs[i]);
  8. } else {
  9. procs[i].Dispose();
  10. }
  11. }
  12. Process[] temp = new Process[list.Count];
  13. list.CopyTo(temp, 0);
  14. return temp;
  15. }

至于 GetCurrentProcess 方法能够这么快,很好理解,毕竟是自己进程,有什么拿不到的呢?其内部调用的是本机方法:

  1. [DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
  2. public static extern int GetCurrentProcessId();

另外,有个有意思的现象:

转载于:https://www.cnblogs.com/walterlv/p/10236424.html

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号