gpt4 book ai didi

c# - 如何测量 C# 中的子进程启动时间?

转载 作者:行者123 更新时间:2023-11-30 17:34:42 25 4
gpt4 key购买 nike

如何在 C# 中测量子进程的启动时间?我目前正在使用以下代码来测量可执行文件的启动时间和想添加子进程执行启动时间,例如 CMD在 Chrome 中运行记事本或新标签页。

这是我现有的用于测量“正常”进程启动时间的代码:

  public static long LaunchProcess(String processFullPath)
{
Process process;
var watch = System.Diagnostics.Stopwatch.StartNew();

try
{
process = Process.Start(processFullPath);
process.WaitForInputIdle();
watch.Stop();
etc....

任何帮助或指导将不胜感激!

最佳答案

所以诀窍是首先检测所有子进程:

var mos = new ManagementObjectSearcher($"Select * From Win32_Process Where ParentProcessID={process.Id}");

然后,我们可以循环收集它们并启动一个新的 Task 来测量执行时间。最后循环遍历 Task 列表并打印耗时。

public Tuple<int, TimeSpan> MonitorProcess(Process process)
{
Stopwatch stopwatch = Stopwatch.StartNew();
process.WaitForExit();
stopwatch.Stop();
return Tuple.Create(process.Id, stopwatch.Elapsed);
}

public void LaunchProcess(String processFullPath)
{
try
{
var tasks = new List<Task<Tuple<int,TimeSpan>>>();
Process process = Process.Start(processFullPath);
if (process == null) return;

// Add my current (parent) process
tasks.Add(Task.Factory.StartNew(()=>this.MonitorProcess(process)));

var childProcesses = new List<Process>();
while (!process.HasExited)
{
// Find new child-processes
var mos = new ManagementObjectSearcher($"Select * From Win32_Process Where ParentProcessID={process.Id}");
List<Process> newChildren = mos.Get().Cast<ManagementObject>().Select(mo => new { PID = Convert.ToInt32(mo["ProcessID"]) })
.Where(p => !childProcesses.Exists(cp => cp.Id == p.PID)).Select(p => Process.GetProcessById(p.PID)).ToList();

// measure their execution time in different task
tasks.AddRange(newChildren.Select(newChild => Task.Factory.StartNew(() => this.MonitorProcess(newChild))));
childProcesses.AddRange(newChildren);
}

// Print the results
StringBuilder sb = new StringBuilder();
foreach (Task<Tuple<int, TimeSpan>> task in tasks) {
sb.AppendLine($"[{task.Result.Item1}] - {task.Result.Item2}");
}

this.output.WriteLine(sb.ToString());
}
catch (Exception ex)
{

}
}

关于c# - 如何测量 C# 中的子进程启动时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42069747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com