CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2010
    Posts
    13

    Timing a program

    I have found that often I am asking which way of solving problems are faster. Thus I will ask how to time a program here so that I can test the runspeed myself. In Java I know you can use

    long start = System.currentTimeMillis();

    and then to display how much time you can do System.out.println(System.currentTimeMillis()-start);

    How would you do this in C++?

    Thanks in advance.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Timing a program

    There are a number of approaches. The simplest is to call clock() or time(), and compare the results, possibly using difftime().

    However, that will only get you accuracy to about 10ms or so, and for many things that isn't good enough.

    On Windows, QueryPerformanceCounter() is a good option. On Unix-based systems, gettimeofday() provides similar accuracy.

    However, the most useful approach is profiling the code as a whole, which actually doesn't involve modifying the code at all. Not sure about Windows, but on Unix-based systems, compile with the -pg flag, then run the program to completion, and then pass the dumped gmon.out file to gprof for the analysis.

  3. #3
    Join Date
    May 2002
    Location
    Lindenhurst, NY
    Posts
    867

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