Thread: More accurate time function

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    15

    More accurate time function

    Using time.h when I code something like this,

    Code:
    #include <iostream>
    #include <time.h>
    #include <system.h>
    
    int main()
    {
    float dif = 0; 
    time_t start, end;
    time(&start);
    //mmmm... function...
    time(&end);
    dif = difftime(end,start);
    std::cout << dif;
    system("pause");
    return 0;
    }
    I get an integer, such as something that takes 1.23 seconds would be listed as 1 second. is there something Im doing wrong or a more accurate function I should be using?
    I am the Uber Noob

  2. #2
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    What OS?

    Kuphryn

  3. #3
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    New York
    Posts
    1,905
    if you're in windows there's multiple timer functions:

    GetTickCount();
    timeGetTime();


    they return time in milliseconds

    http://msdn.microsoft.com/library/de...ttickcount.asp

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    You can get more precision by making an unwarranted (but likely to be true) assumption about the clock_t type.
    Code:
    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    int
    main()
    {
      double  dif; 
      clock_t start;
    
      start = clock();
      for (int i = 0; i < 1000000; i++) {
        cout<<"";
      }
      dif = (static_cast<double>(clock()) - start) / CLOCKS_PER_SEC;
      cout<< dif;
    
      return 0;
    }
    The unwarranted assumption is that the clock_t type can handle arithmetic operations more complex than comparison with (clock_t)-1. However, I don't know of an implementation where this isn't true. Use this approach at your own risk.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sending an email in C program
    By Moony in forum C Programming
    Replies: 28
    Last Post: 10-19-2006, 10:42 AM
  2. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  3. The Timing is incorret
    By Drew in forum C++ Programming
    Replies: 5
    Last Post: 08-28-2003, 04:57 PM
  4. Replies: 5
    Last Post: 02-08-2003, 07:42 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM