Description
This article describes two methods of measuring time difference.
The first method uses the Win32 API function GetTickCount(), and
the second method uses the clock() function. Both methods produce
similar (but not identical) results. This project uses a form and
a TButton: Button1.
TimeDifference.cpp
#include <vcl.h>
#pragma hdrstop
#include "TimeDifference.h"
#include //clock_t definition
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//-----------------------------------------------------------------------
long double Count( const long double max )
{
long double count = 0;
for ( long double i = 0; i< max; i++ )
count += 1;
return count;
}
//-----------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
String S_API;
String S_clock;
const long double NUMBER_MAX = 100000000; //100 millions
//GetTickCount() method:
DWORD t1 = GetTickCount(); //Win32 API
long double count1 = Count( NUMBER_MAX );
DWORD t2 = GetTickCount(); //Win32 API
DWORD Dt = t2 - t1;
S_API = String( Dt ) + " mS " + FloatToStr( Dt/1000.0 ) + " S" ;
//clock() method:
clock_t t3 = clock();
long double count2 = Count( NUMBER_MAX );
clock_t t4 = clock();
clock_t Dt2 = t4 - t3;
S_clock = String( Dt2 ) + " mS " + FloatToStr( Dt2/1000.0 ) + " S" ;
//Display Time Difference
ShowMessage( "GetTickCount() method: " + S_API
+ "\nclock() method: " + S_clock
+ "\ncont1 =" + String( FloatToStr( count1 ))
+ "\ncont2 =" + String( FloatToStr( count2 )) );
}
//---------------------------------------------------------------------------
TimeDifference.h
#ifndef TimeDifferenceH
#define TimeDifferenceH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published: // IDE-managed Components
TButton *Button1;
void __fastcall Button1Click(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif
Homepage
Copyright © 1997-2002 Rodolfo A. Frino. All rights reserved.