Thread: time measurement using clock() and time()

  1. #1
    Registered User
    Join Date
    Jun 2004

    time measurement using clock() and time()


    I want to measure the execution time of some part of my program. Therefore I've written something like

    clock_t startTime = clock();
    // do operations
    clock_t endTime = clock();
    std::cout << "elapsed time: " << (double)(endTime - startTime) / CLOCKS_PER_SEC
        << std::endl;
    This seems to work fine under Windows. However, running the same program under UNIX (sunOS) produced results that didn't appear to be correct to me.

    Therefore, I decided double check the time measurement using the time() function:

    time_t startTime = time(NULL);
    clock_t startClk = clock();
    // do operations
    clock_t endClk = clock();
    time_t endTime = time(NULL);
    std::cout << "elapsed time: " << (double)(endClk - startClk) / CLOCKS_PER_SEC
        << std::endl;
    std::cout << "elapsed time (using time()): " << endTime - startTime << std::endl;
    This program confirmed my doubts... I got results like 204.04 for the measurement using clock() and 426 for the measurement using time(). CLOCKS_PER_SEC has a value of 1000000.

    The time measurement works fine under windows, i.e. the measurements using clock() and time() yield the same results that appear reasonable to me.

    Can somebody explain me what is going wrong under UNIX? And how to solve the problem? The reason I don't want to use time() is, that I have some parts where a resolution of 1 second is not sufficient.



  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Journey time prog 1 minute wrong
    By mike_g in forum C Programming
    Replies: 4
    Last Post: 10-12-2006, 03:41 AM
  2. Read and set\change system time
    By Hexxx in forum C++ Programming
    Replies: 9
    Last Post: 01-02-2006, 07:11 AM
  3. Real time clock
    By caduardo21 in forum C++ Programming
    Replies: 5
    Last Post: 03-19-2005, 12:22 PM
  4. inputting time in separate compilation
    By sameintheend01 in forum C++ Programming
    Replies: 6
    Last Post: 03-13-2003, 04:33 AM
  5. Is this really true or it's just science fiction?
    By Nutshell in forum A Brief History of
    Replies: 145
    Last Post: 04-09-2002, 06:17 PM