Timing In C++

This is a discussion on Timing In C++ within the C++ Programming forums, part of the General Programming Boards category; Hey Folks. Question here. I am writing a program in C++ in linux. I need to time a piece of ...

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    34

    Timing In C++

    Hey Folks. Question here. I am writing a program in C++ in linux. I need to time a piece of code. Currently I am using the times function in <sys/times.h>. It gets me the time alright (time differece between start and end of code segment). However, I need a greater accuracy (3 decimal places at least). I want the same degree of accuracy as when I run the "time <progname>" command. For example, for one of my programs the output was:

    real 0m0.067s
    user 0m0.064s
    sys 0m0.004s

    when using the "time <programname>. When using times function within my program I get the following: 0.07. If I increase the precision of the output, they are just zeros. Is there any way to have the same degree of accuracy as a "time" command?

  2. #2
    l'Anziano DavidP's Avatar
    Join Date
    Aug 2001
    Location
    Plano, Texas, United States
    Posts
    2,738
    If you are using Linux, as you say, you should be able to use timespec, which gives you nanosecond precision in timing.

    Here is a link: Timespec Reference

    In that reference, they say to include os_time.h, but when I used it, I just included time.h, and it worked fine, so you should be able to do it with time.h.

    Here is an example on how to use it:

    Code:
    struct timespec tp;
    clock_gettime ( CLOCK_REALTIME, &tp );
    Seconds = tp.tv_sec;
    NanoSeconds = tp.tv_nsec;
    My Website

    "Circular logic is good because it is."

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Timing basic operations in C++
    By StevenGarcia in forum C++ Programming
    Replies: 9
    Last Post: 09-18-2007, 02:10 AM
  2. Performance Timing Function
    By rosicky2005 in forum C++ Programming
    Replies: 11
    Last Post: 05-31-2007, 03:09 PM
  3. My Timing System
    By jmd15 in forum Windows Programming
    Replies: 4
    Last Post: 01-01-2006, 10:43 PM
  4. Games - timing
    By Magos in forum Game Programming
    Replies: 7
    Last Post: 03-06-2004, 10:32 AM
  5. Timing in Windows
    By steinberg in forum Windows Programming
    Replies: 3
    Last Post: 07-14-2002, 12:43 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21