如何在c#中测量子进程启动时间?

时间:2017-02-06 14:07:30

标签: c# performance process profiling system.diagnostics

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

这是我现有的测量代码" normal"流程启动时间:

  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 个答案:

答案 0 :(得分:1)

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

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)
    {

    }
}