c++timetdatetime

Calculating time length between operations in c++


The program is a middleware between a database and application. For each database access I most calculate the time length in milliseconds. The example bellow is using TDateTime from Builder library. I must, as far as possible, only use standard c++ libraries.

AnsiString TimeInMilliseconds(TDateTime t) {
      Word Hour, Min, Sec, MSec;
      DecodeTime(t, Hour, Min, Sec, MSec);
      long ms = MSec + Sec * 1000 + Min * 1000 * 60 + Hour * 1000 * 60 * 60;
      return IntToStr(ms);
  }
  // computing times
   TDateTime SelectStart = Now();
   sql_manipulation_statement();
   TDateTime SelectEnd = Now();

Solution

  • On both Windows and POSIX-compliant systems (Linux, OSX, etc.), you can calculate the time in 1/CLOCKS_PER_SEC (timer ticks) for a call using clock() found in <ctime>. The return value from that call will be the elapsed time since the program started running in milliseconds. Two calls to clock() can then be subtracted from each other to calculate the running time of a given block of code.

    So for example:

    #include <ctime>
    #include <cstdio>
    
    clock_t time_a = clock();
    
    //...run block of code
    
    clock_t time_b = clock();
    
    if (time_a == ((clock_t)-1) || time_b == ((clock_t)-1))
    {
        perror("Unable to calculate elapsed time");
    }
    else
    {
        unsigned int total_time_ticks = (unsigned int)(time_b - time_a);
    }
    

    Edit: You are not going to be able to directly compare the timings from a POSIX-compliant platform to a Windows platform because on Windows clock() measures the the wall-clock time, where-as on a POSIX system, it measures elapsed CPU time. But it is a function in a standard C++ library, and for comparing performance between different blocks of code on the same platform, should fit your needs.