CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    [RESOLVED] How to time a loop

    In a Windows Forms app I have a lengthy loop (more precisely: one that does a lot of iterations) and I want to know how long that takes. So I wrapped the loop between the lines

    Code:
      DateTime dtStart=DateTime::Now;
    and

    Code:
      Diagnostics::Debug::WriteLine("Elapsed time: {0} ms",(DateTime::Now-dtStart).Milliseconds);
    But that method doesn't give me reasonable results. I'm not talking about inaccuracies due to the limited resolution of the system ticker, I'm talking about it giving me results somewhere between 300 and 700 ms, while the actual time taken for the calculation is > 20,000 ms (roughly checked by looking at my watch).

    What is the reason for that extreme inaccuracy and how can I get rid of it? However, I'm not looking for something sophisticated like serious profiling. It doesn't have to be that precise, and I don't have tools for this at hand, as I'm using VC++ Express.

    TIA

  2. #2
    Join Date
    Jul 2002
    Posts
    2,543

    Re: How to time a loop

    Try StopWatch class which has high precision and designed exactly for this purpose. If you still have strange results, post the whole code fragment.

  3. #3
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Resolved Re: How to time a loop

    Nice class I didn't know yet! Thank you for the tip, now I'm getting reasonable results.

    But I'm still wondering how the DateTime class could be that far off...

  4. #4
    Join Date
    Jul 2002
    Posts
    2,543

    Re: [RESOLVED] How to time a loop

    DateTime:: Millisecond Property
    The milliseconds component, expressed as a value between 0 and 999.

  5. #5
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Red face Re: [RESOLVED] How to time a loop

    Quote Originally Posted by Alex F View Post
    DateTime:: Millisecond Property
    The milliseconds component, expressed as a value between 0 and 999.
    Uuuh... :facepalms:

    But at least that was an occasion to learn about the Stopwatch class.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured