繁体   English   中英

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

[英]How do I measure child process launch time in c#?

如何在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)
    {

    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM