Search code examples
c#timestartup

How to get time it takes for an application to startup?


I am writing a C# application that needs to be able to tell how much time it takes for a certain application to open. I am using the Stopwatch class as my timer. Start time is easy since I set it exactly with the call to run the .exe. The problem is finding out how to time when the program is done opening. The only thing I could think of to test this is using a PerformanceCounter object and checking when CPU% is less than a certain number using a while loop.

At the moment I am using PerformanceCounter, but I am not having luck with it displaying the CPU% (it's always displaying 0). My guess for this is either that the application opens up faster than the PerformanceCounter can check for the CPU% or that the PerformanceCounter is not seeing the process name because I'm calling it too quickly (I highly doubt the latter due to the fact that I think I would get errors if this happened).

Are there any other ways to have this problem solved? Is there something I might be doing wrong that is giving me a 0 CPU% all the time? I am not looking for external tools outside of my application. Here is a sample of my code:

otherApp = new otherApplication.Application();
PerformanceCounter cpuCounter = new PerformanceCounter("Process",
"% Processor Time", "otherApplication");
//This next line is to check if PerformanceCounter object is working
//MessageBox.Show(cpuCounter.NextValue().ToString());
stopwatch.Start();
while (cpuCounter.NextValue() > 10)
{
}
stopwatch.Stop();

Edited: Changed code to say otherApp and otherApplication instead of myApp and myApplication, so that it may be easier to understand.


Solution

  • You may be better off using a known location in your code (a particular method that's called when all initialization work is complete) rather than relying on CPU utilization as a heuristic.