Tickcount and milliseconds in C++ - c++

How do I convert from TickCounts to Milliseconds?
this is what I used:
long int before = GetTickCount();
long int after = GetTickCount();
I want the difference of it in seconds.

int seconds = (after - before) /1000;

for more precision, there is also QueryPerformanceCounter()

int seconds = (after - before + 500) / 1000;
or:
double seconds = (after - before) / 1000.0;

GetTickCount() returns the time in milliseconds. so (after - before)/<milli equivalent> should give you time in seconds

I'm not sure what OS/platform you're using, but there should be a call that returns the tick time in milliseconds.
time = after - before * <tick time in milliseconds>;
Edit:
I see that this is a Windows function that returns milliseconds already. The other answers are better.

Related

Get System Time In MilliSeconds as an int/double

I am new to c++ but I just cant get this to work at all. I am trying to get the system current time in ms and do something with it but it wont work what I have tried.
Qt
QDateTime qt = new QDateTime();
int x = qt.currentDateTimeUtc();
if(x%5 ==0){
//something
}
c++
double sysTime = time(0);
if(sysTime%5.00 ==0.00){
}
I get invalid operands of type double to binary operator error. I have no idea why? Can anyone point in the right direction
For QT, try using the function QDateTime::toMSecsSinceEpoch()
http://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch
This will return a qint64 http://doc.qt.io/qt-5/qtglobal.html#qint64-typedef
If you're trying to get the unix timestamp in milliseconds in C you can try this code:
include "time.h"
...
time_t seconds;
time(&seconds);
unsigned long long millis = (unsigned long long)seconds * 1000;
Though please note this is multiplied by 1000 - it looks like milliseconds but the accuracy is that of seconds - which judging by your x % 5 code might be enough if you're trying to do something every 5 seconds, so the following should be enough:
time_t seconds; time(&seconds);

Adding two epoch millseconds in C++

My goal is to determine expiry of an item to when it was acquired(bought) and when it is sold.There is a TTL value associated with each of the item.
I am doing following :
time_t currentSellingTime;
long currentSystemTime = time(&currentSellingTime); // this gives me epoch millisec of now()
long TTL = <some_value>L;
long BuyingTime = <some_value> // this is also in epoch millsec
if(currentSystemTime > TTL+BuyingTime))
{
//throw exception
// item is expired
}
My question is how to sum two epoch millisec and compare it with another epoch millsec in C++
There may be some misconceptions on how time() works:
epoch time as given by time() is expressed in seconds, not millseconds
time returns the current time value and can optionally set current time in the variable given as its sole argument. This means that
long currentSystemTime = time(&currentSellingTime);
will set both currentSystemTime and currentSellingTime to the current time, and that's probably not what you intend to do... You should probably do
long currentSystemTime = time(NULL);
or
time(&currentSellingTime);
but the "double form" you are using is quite suspicious. For completeness' sake the MS Help reference for time()
You want to use another function, as as previously pointed out, time() returns seconds. Try:
#include <time.h>
long current_time() {
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return t.tv.sec * 1000l + t.tv_nsec / 1000000l;
}
Your code should work then. This approach is also POSIX compatible. Example usage:
const long TTL = 100;
long start_time = current_time();
while (!(current_time() > start_time + TTL))
{
// do the stuff that can expire
}
note: I know that the condition in the while loop can be constructed differently, but this way it is more like "until not expired".

C++ Timer Problem

I've written a timer class. After starting the timer, I would like to know if 20 seconds has been passed or not, if it is, I would like to call a function or perform a block of code. That class doesn't work but I Don't know why .
EDIT: By it doesn't work I mean that isTimeTout(seconds) always return true; I would like just to see if few seconds has been passed, and based on that do an action.
class timer {
private:
unsigned long begTime;
public:
void start() {
begTime = clock();
}
unsigned long elapsedTime() {
return ((unsigned long) clock() - begTime) / CLOCKS_PER_SEC;
}
bool isTimeout(unsigned long seconds) {
return seconds >= elapsedTime();
}
};
clock() measures CPU time not wall time. Try using time() along with difftime() instead.
Since you're on Windows, you can stick with using clock().
The error is here:
return seconds >= elapsedTime();
it should be:
return seconds <= elapsedTime();
What you have right now will return true when less than 20 seconds has elapsed. Flipping the comparison should fix it.
Try using time() and difftime() like stated above. I've had this problem before too :)

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();
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.
On windows you can use GetTickCount (MSDN) Which will give the number of milliseconds that have elapsed since the system was started. Using this before and after the call you get the amount of milliseconds the call took.
DWORD start = GetTickCount();
//Do your stuff
DWORD end = GetTickCount();
cout << "the call took " << (end - start) << " ms";
Edit:
As Jason mentioned, Clock(); would be better because it is not related to Windows only.

elapsed time with unsigned tickCount / Wrapping

i have a own GetTickCount() function returning an unsigned int (the count rolls over to zero on 0xFFFFFFFF)
i cant measure an elapsed time with:
unsigned int elapsed;
unsigned int start = GetTickCount();
LongOperation();
unsigned int stop = GetTickCount();
if (stop >= start )
elapsed = stop - start;
else
elapsed = (INT_MAX - start) + stop;
is this the same if i do a cast to signed (the time span i measure is always less than what can be represented in a signed integer - i think about 24 days) ? :
int start = (int)GetTickCount();
LongOperation();
int elapsedTime = (int)GetTickCount() - start;
if i look at the .net Environmet.TickCount property:
TickCount will increment from zero to Int32..::.MaxValue for approximately 24.9 days, then jump to Int32..::.MinValue, which is a negative number, then increment back to zero during the next 24.9 days.
so when i cast my GetTickCount() function to a signed integer i should get the behaviour from .net (wrapping occurs on 0x7FFFFFFF->0x80000000) ?
with this should be possible do measure the elapsed time as follow (seen in another post):
int start = Environment.TickCount;
DoLongRunningOperation();
int elapsedTime = Environment.TickCount - start;
The prototype for GetTickCount() in C++ in Windows is:
DWORD WINAPI GetTickCount(void);
So, I would code it like this (similar to the other answers):
DWORD start = GetTickCount();
dosomething();
DWORD elapsed = GetTickCount() - start;
Will measure elapsed times up to the maximum number DWORD can represent.
As others have said, with unsigned arithmetic, you don't need to worry about the counter wrapping around - try it yourself...
Also check GetTickCount64() and QueryPerformanceCounter()/QueryPerformanceFrequency(). GetTickCount64() will allow you to measure longer intervals, but it is not supported on all versions of Windows, while QueryPerformanceCounter() allows you to measure to much higher resolution and accuracy. For example, on some Windows versions, GetTickCount() may only be accurate to about 18ms while QueryPerformanceCounter() will be better than 1us.
I'm not sure GetTickCount() is the preferred function to your problem.
Can't you just use QueryPerformanceFrequency()? There's a nice example at
http://msdn.microsoft.com/en-us/library/ms644904%28v=VS.85%29.aspx
In C++, if you stick with unsigned, the code will work:
unsigned int start = gettickcount();
DoLongRunningOperation();
unsigned int elapsedTime = static_cast<unsigned int>(gettickcount()) - start;
The reason you want to stick with unsigned is that unsigned arithmetic is required to use modulo arithmetic which is what you want in this case.