Search code examples
c#stopwatch

Estimate the amount of time it takes to complete a programme in C#


I am using Stopwatch and I would like to estimate how long it takes from start to finish.

It looks like a very simple complex. I instantiated stopwatch, start it, then stop it and then by writing a method .elapsed it should provide me with the time it takes from start to stop.

Unfortunately it always provides me with 00:00:00.

Do I have to set something specific to my culture on my PC or?

I have also tried .StartNew() but to no avail.

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        string juniorDevOpsFolder = "JuniorDevOps";
        string targetPath = Directory.GetCurrentDirectory();
        int endIndex = targetPath.IndexOf(juniorDevOpsFolder);
        var juniorDevOpsPath = targetPath.Substring(0, endIndex + juniorDevOpsFolder.Length);
        string directory = "Files";
        string targetDirectory = Path.Combine(juniorDevOpsPath, directory);
        ProcessDirectory(targetDirectory);
        stopwatch.Stop();

        // Write hours, minutes and seconds.
        Console.WriteLine("Time elapsed: {0:hh\\:mm\\:ss}", stopwatch.Elapsed);

Again, the output is 00:00:00


Solution

  • Your program is taking less than one second to execute, so formatted stopwatch.Elapsed is printing 00:00:00 to console. Try stopwatch.ElapsedMilliseconds instead of formatted stopwatch.Elapsed.

    something like

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
    
        //Your business logic
    
        stopwatch.Stop();
        Console.WriteLine($"Elapsed milliseconds : {stopwatch.ElapsedMilliseconds}" );