TimeSpan accuracy

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hsachdevah
    New Member
    • Nov 2008
    • 20

    #1

    TimeSpan accuracy

    Hello,

    I am using TimeSpan to calculate the time my program takes.
    Here's the code

    Code:
    DateTime start = DateTime.Now;
    
    //**my code here
    
    DateTime end = DateTime.Now;
    span = end.Subtract(start);
    
    ResultUserForm.Controls["lblTimer"].Text = string.Concat(span.Milliseconds.ToString(), "ms");

    but the time I get in accuracy of 15ms.
    I get either 15ms, or 31ms, or 46ms. And sometimes 0ms
    I want it to show things like 8ms too, but it shows 0ms.

    How to find a solution to this.
  • cloud255
    Recognized Expert Contributor
    • Jun 2008
    • 427

    #2
    Well you can't really tell your program how long it should take (unless you use actual thread delays) so what is the problem? If the program never takes 8ms to execute then it never takes that amount of time. Also bear in mind that it might be 0 milliseconds but several hundredths of a second may have passed eg:

    0:00:00:120 //h:mm:ss

    TimeSpan.Millis econds will never show how many seconds, minutes etc have passed...

    As far as the accuracy, this depends on the clock speed at which your CPU is running (I think, my hardware knowledge is pretty limited), if that is the case then a faster CPU will make time measurement more accurate... but with modern machines and the scope of values you want to measure I cant image that the result is incorrect...

    Comment

    • Plater
      Recognized Expert Expert
      • Apr 2007
      • 7872

      #3
      You would want to use the .TotalMilliseco nds property of a timespan then.
      .Milliseconds returns JUST the millisecond portion of the time.
      .TotalMilliseco nds returns the entire structure in terms of milliseconds

      Comment

      • PRR
        Recognized Expert Contributor
        • Dec 2007
        • 750

        #4
        Look into Stopwatch Class . Stopwatch class is used to measure execution time of a method...

        MSDN
        Code:
        class Program
        {
            static void Main(string[] args)
            {
                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();
                Thread.Sleep(10000);
                stopWatch.Stop();
                // Get the elapsed time as a TimeSpan value.
                TimeSpan ts = stopWatch.Elapsed;
        
                // Format and display the TimeSpan value.
                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                    ts.Hours, ts.Minutes, ts.Seconds,
                    ts.Milliseconds / 10);
                Console.WriteLine(elapsedTime, "RunTime");
            }
        }

        Comment

        Working...