Search code examples
c#runtimestopwatch

How make time elapsed method?


I need a method that give me the time elapsed awhile my process. I call it at start the process and call it again at finish the process, and the method print the total time elapsed.

This is my method, but always print the time in 00:00. Why is happening this??

public void GetTimeElapsed(string filePath, int logSelected, bool time, IUserOptions userOptions)
    {
        var stopwatch = new System.Diagnostics.Stopwatch();

        LogBinaryWriter BinaryWriter = new LogBinaryWriter();
        string timeElapsed = "";
        if(time == true)
        {
            stopwatch.Start();
        }
        if (time == false) 
        {
            stopwatch.Stop(); 
            TimeSpan timeSpan = stopwatch.Elapsed;
            timeElapsed = (string.Format("\nFile Generated: {0}\nTime Elapsed: {1} minute(s) {2} second(s)",
            BinaryWriter.CreateLogFileName(filePath, Convert.ToInt32(logSelected)),
            timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10 + "\n"));
            userOptions.DisplayUserMessage(timeElapsed);

        }           
    } 

Solution

  • Your stopwatch variable is local. When you call the function a second time, it's initialized again.

    You need to move the declaration up to class level.

    System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
    
    public void GetTimeElapsed(string filePath, int logSelected, bool time, IUserOptions userOptions)
    {
       ... etc