Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process.Start() significantly slower than executing in console

Tags:

c#

.net

I have performance problems executing an .exe using Process.Start(). The execution takes roughly 5 times longer from .NET then it does from console. What can cause this? Here is a test program:

  public static void Main(string[] argv)
  {       
     for (int i = 0; i < 10; i++)
     {
        ProcessStartInfo psi = new ProcessStartInfo(ExePath, Args);
        Process ps = new Process {StartInfo = psi};
        Stopwatch sw = Stopwatch.StartNew();
        ps.Start();
        ps.WaitForExit();
        sw.Stop();
        Console.WriteLine(i+" Elapsed time: " + sw.ElapsedMilliseconds + "ms.");
        Thread.Sleep(1000);
     }
  }

The result is this:

 0 Elapsed time 4310ms.
 1 Elapsed time 4330ms.
 2 Elapsed time 4280ms.
 ...

Running it in a cmd window returns almost immediately (sub 1 second execution). Tried timing it in the console using

> powershell Measure-Command { cmd /c start /wait %EXE% %ARGS% } 

Which shows around 750ms for the execution, which is a good 5-6 times faster. Not sure I did that right, but 750ms feels like a likely execution time.

At first I was reading std out and thought it was related to this, see e.g. Process takes longer to finish than in CMD and similar questions. Obviously in the simple test program I'm not reading any output now, just executing.

Possible causes I have alreay ruled out that cause no difference in exec time:

  • Debugger/no debugger
  • Debug/Release build of .NET host process
  • Working directory
  • Platform of host .NET process Any/x86/x64 (exe is native x64)
  • UseShellExecute true/false

What I do know about the executable (It's the rust statement completion tool 'racer' https://github.com/phildawes/racer) is that it will go off and open lots of files. Could that matter when coming from the .NET host, e.g. wrt. security, that causes the slowdown? What else could cause the huge performance difference?

like image 282
Anders Forsgren Avatar asked Nov 27 '14 10:11

Anders Forsgren


2 Answers

The difference in running time in this case was due to different versions of the executed (racer.exe) file, and had nothing to do with the fact that one was being executed from a .NET process and the other from the command line.

There shouldn't be a difference when running an executable from .NET as it is simply using system calls to execute the program.

like image 82
Pablo Montilla Avatar answered Nov 15 '22 21:11

Pablo Montilla


    ps.WaitForExit();

That's the statement that makes the difference. Your cmd.exe command doesn't wait for the process to terminate. Either remove WaitForExit() or use "cmd /c start /wait %EXE% %ARGS%" to compare apples to oranges.

Or in other words, you didn't measure how long it took to start a process, you measured how long the process was running.

like image 25
Hans Passant Avatar answered Nov 15 '22 22:11

Hans Passant