我该如何在C#中测量子进程启动时间?

3

我该如何在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....

任何帮助或指导将不胜感激!
1个回答

1

因此,关键在于首先检测所有子进程:

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

然后,我们可以在循环中收集它们,并启动一个新的任务来测量执行时间。最后,通过任务列表循环并打印经过的时间。
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)
    {

    }
}

你,朋友,是个天才!非常感谢你! - Itamar Levy
很高兴我能帮到你,@ItamarLevy。如果这个或任何答案解决了你的问题,请考虑通过点击勾选标记接受它。这向更广泛的社区表明你已经找到了解决方案,并为回答者和你自己赢得了一些声誉。没有义务这样做。 - Ofir Winegarten

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接