Regarding getting time in milliseconds - c

I am working on logger using C language on QNX platform using Momnetics to print time in following format
2010-11-02 14:45:15.000
I able to get date, hour, minutes, and seconds using
time(&timeSpec);
struct tm gmt;
int iSysTimeSec = timeSpec;
gmtime_r((time_t *)&iSysTimeSec, &gmt);
sprintf(&MsgStamp[0], SYS_MSG_STAMP_PRINTF_FORMAT, gmt.tm_year+1900, gmt.tm_mon + 1, gmt.tm_mday, gmt.tm_hour, gmt.tm_min, gmt.tm_sec, iSysTimeMs );
Question is how do i get milliseconds granularity using QNX Momentics.
I tried to get granulaity for milliseconds using QNX specific
int iSysTimeMs = ( (ClockCycles () * 1000) / SYSPAGE_ENTRY(qtime)->cycles_per_sec ) % 1000;
but i want to do this POSIX way so that it is portable. How do we do this?
Thanks!
Venkata

In QNX6 You can use the clock_gettime to have the max granularity
allowed by system.
struct timespec start;
clock_gettime( CLOCK_REALTIME, &start);

The gettimeofday() system call will return a structure holding the current Unix time in seconds and the number of microseconds belonging to the current second.
To get the total number of microseconds:
struct timeval tv;
gettimeofday(&tv, NULL);
u_int64_t now = tv.tv_sec * 1000000ULL + tv.tv_usec;

Related

C - Timing my program in seconds with microsecond precision on

I'm trying to find out the user time (on a Linux machine) of C program I've written. Currently I'm calling gettimeofday() once at the beginning of my code and once at the end. I'm using the timeval struct and difftime(stop.tv_sec,start.tv_sec) to get the number of seconds elapsed. This returns whole seconds, like "1.000000". However, my project requires that my program be timed in seconds with microsecond precision, for example "1.234567". How can I find this value? I know gettimeofday() also records microseconds in .tv_usec, but I'm not sure how to use this value and format it correctly.
Use the timersub function. It takes three arguments: the first is the initial time, the second the final one, and the third is the result (the diference). All of the three arguments are pointers to timeval struct.
Try putting the initial time into storage then subtract that from the final time when you are done.
storedValue = timer.tv_sec + 0.000001 * timer.tv_usec
timer.tv_sec + 0.000001 * timer.tv_usec - storedValue
If you want microseconds:
long long usec;
usec = tv.tv_sec;
usec *= 1000000;
usec += tv.tv_usec;
If you want fractional seconds [floating point]:
double asec;
asec = tv.tv_usec;
asec /= 1e6;
asec += tv.tv_sec;
Here are some complete functions:
// tvsec -- get current time in absolute microseconds
long long
tvsec(void)
{
struct timeval tv;
long long usec;
gettimeofday(&tv,NULL);
usec = tv.tv_sec;
usec *= 1000000;
usec += tv.tv_usec;
return usec;
}
// tvsecf -- get current time in fractional seconds
double
tvsecf(void)
{
struct timeval tv;
double asec;
gettimeofday(&tv,NULL);
asec = tv.tv_usec;
asec /= 1e6;
asec += tv.tv_sec;
return asec;
}
Note: If you want even higher accuracy (e.g. nanoseconds), you can use clock_gettime(CLOCK_REALTIME,...) and apply similar conversions

C find elapsed time in C Linux

I have to calculate the time taken by a function to complete.
This function is called in a loop and I want to find out the total time.
Usually the time is very less in either nano or micro seconds.
To find out the elapsed time I used functions gettimeofday() using struct timeval and clock_gettime() using struct timespec.
Problem is time return by timeval in seconds is correct but in micro seconds wrong.
Similarly the time returned by timespec in nano seconds is wrong.
Wrong in the sense they do not tally with the time returned in seconds.
For clock_gettime() I tried both CLOCK_PROCESS_CPUTIME_ID and CLOCK_MONOTONIC.
Using clock() also does not help.
Code snippet:
struct timeval funcTimestart_timeval, funcTimeEnd_timeval;
struct timespec funcTimeStart_timespec, funcTimeEnd_timespec;
unsigned long elapsed_nanos = 0;
unsigned long elapsed_seconds = 0;
unsigned long diffInNanos = 0;
unsigned long Func_elapsed_nanos = 0;
unsigned long Func_elapsed_seconds = 0;
while(...)
{
gettimeofday(&funcTimestart_timeval, NULL);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &funcTimeStart_timespec);
...
demo_func();
...
gettimeofday(&funcTimeEnd_timeval, NULL);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &funcTimeEnd_timespec);
elapsed_seconds = funcTimeEnd_timeval.tv_sec - funcTimestart_timeval.tv_sec;
Func_elapsed_seconds+= elapsed_seconds;
elapsed_nanos = funcTimeEnd_timespec.tv_nsec - funcTimeStart_timespec.tv_nsec;
Func_elapsed_nanos+ = elapsed_nanos;
}
printf("Total time taken by demo_func() is %lu seconds( %lu nanoseconds )\n", Func_elapsed_seconds, Func_elapsed_nanos );
Printf output:
Total time taken by demo_func() is 60 seconds( 76806787 nanoseconds )
See that the time in seconds and nanoseconds do not match.
How to resolve this issue or any other appropriate method to find elapsed time?
Did you read the documentation of time(7) and clock_gettime(2)? Please read it twice.
The struct timespec is not supposed to express twice the same time. The field tv_sec gives the second part ts, and the field tv_nsec gives the nanosecond part tn to express the time t = ts + 10-9 tn
I would suggest to convert that to a floating point, e.g.
printf ("total time %g\n",
(double)Func_elapsed_seconds + 1.0e-9*Func_elapsed_nanos);
Using floating point is simpler and generally the precision is enough for most needs. Otherwise, when you add or substract struct timespec you need to handle the case when the added/substracted tv_nsec field sum/difference is negative or more than 1000000000....
The problem is you are printing/comparing wrong values.
76,806,787 nanoseconds is equal to ~76 milliseconds, you cannot compare it with 60 seconds.
You are ignoring the time in seconds stored in funcTimeEnd_timespec.tv_sec.
You should also print funcTimeEnd_timespec.tv_sec - funcTimeStart_timespec.tv_sec, and as #Basile Starynkevitch suggested, add with it the nanoseconds part after multiplying it with 10e-9. Then you can compare time elapsed shown by both functions.
I am replying to the previous answers as answer as I wanted to paste code snippets.
Question is to find out elapsed time whether
first I should subtract the corresponding times with each other and then add
(end.tv_sec - start.tv_sec) + 1.0e-9*(end.tv_nsec - start.tv_nsec)
or
first add the times and then compute the difference
(end.tv_sec + 1.0e-9*end.tv_nsec) - (start.tv_sec + 1.0e-9*start.tv_nsec)
In the first case quite often end.tv_nsec is less in number then start.tv_nsec and hence the difference becomes negative number nd this give me wrong number.

Where does v4l2_buffer->timestamp value starts counting?

I am trying to use v4l2_buffer's timestamp value (type timeval) to synchronize images captured from a UVC webcam to external events.
However the timestamp is not the same as the system time, or the up time, etc:
printf("image captured at %ld, %ld\n",
buffer->timestamp.tv_sec,
buffer->timestamp.tv_usec);
struct timeval tv;
gettimeofday(&tv, 0);
printf("current time %ld, %ld\n", tv.tv_sec, tv.tv_usec);
Results in
image captured at 367746, 476270
current time 1335083395, 11225
My uptime is 10 days.
According to http://comments.gmane.org/gmane.linux.drivers.video-input-infrastructure/39892 some v4l2 drivers (including the UVC one) do not use the realtime clock (wall time) but rather a monotonic clock that counts from a not specified point in time. On Linux, this is the boot time (i.e. uptime), however (and I suspect this is the cause of your mismatch) only the time that the computer was actually running (i.e. this clock does not run when the computer is suspended).
If you have the OP's problem, and you're trying to get to epoch timestamps for each frame, you can use the code snippet below to do so.
#include <time.h>
#include <math.h>
//////////////////////
//setup:
long getEpochTimeShift(){
struct timeval epochtime;
struct timespec vsTime;
gettimeofday(&epochtime, NULL);
clock_gettime(CLOCK_MONOTONIC, &vsTime);
long uptime_ms = vsTime.tv_sec* 1000 + (long) round( vsTime.tv_nsec/ 1000000.0);
long epoch_ms = epochtime.tv_sec * 1000 + (long) round( epochtime.tv_usec/1000.0);
return epoch_ms - uptime_ms;
}
//stick this somewhere so that it runs once, on the startup of your capture process
// noting, if you hibernate a laptop, you might need to recalc this if you don't restart
// the process after dehibernation
long toEpochOffset_ms = getEpochTimeShift();
//////////////////////
//...somewhere in your capture loop:
struct v4l2_buffer buf;
//make the v4l call to xioctl(fd, VIDIOC_DQBUF, &buf)
//then:
long temp_ms = 1000 * buf.timestamp.tv_sec + (long) round( buf.timestamp.tv_usec / 1000.0);
long epochTimeStamp_ms = temp_ms + toEpochOffset_ms ;
printf( "the frame's timestamp in epoch ms is: %ld", epochTimeStamp_ms);

Calculating elapsed time in a C program in milliseconds

I want to calculate the time in milliseconds taken by the execution of some part of my program. I've been looking online, but there's not much info on this topic. Any of you know how to do this?
Best way to answer is with an example:
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
/* Return 1 if the difference is negative, otherwise 0. */
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1)
{
long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
result->tv_sec = diff / 1000000;
result->tv_usec = diff % 1000000;
return (diff<0);
}
void timeval_print(struct timeval *tv)
{
char buffer[30];
time_t curtime;
printf("%ld.%06ld", tv->tv_sec, tv->tv_usec);
curtime = tv->tv_sec;
strftime(buffer, 30, "%m-%d-%Y %T", localtime(&curtime));
printf(" = %s.%06ld\n", buffer, tv->tv_usec);
}
int main()
{
struct timeval tvBegin, tvEnd, tvDiff;
// begin
gettimeofday(&tvBegin, NULL);
timeval_print(&tvBegin);
// lengthy operation
int i,j;
for(i=0;i<999999L;++i) {
j=sqrt(i);
}
//end
gettimeofday(&tvEnd, NULL);
timeval_print(&tvEnd);
// diff
timeval_subtract(&tvDiff, &tvEnd, &tvBegin);
printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec);
return 0;
}
Another option ( at least on some UNIX ) is clock_gettime and related functions. These allow access to various realtime clocks and you can select one of the higher resolution ones and throw away the resolution you don't need.
The gettimeofday function returns the time with microsecond precision (if the platform can support that, of course):
The gettimeofday() function shall
obtain the current time, expressed as
seconds and microseconds since the
Epoch, and store it in the timeval
structure pointed to by tp. The
resolution of the system clock is
unspecified.
C libraries have a function to let you get the system time. You can calculate elapsed time after you capture the start and stop times.
The function is called gettimeofday() and you can look at the man page to find out what to include and how to use it.
On Windows, you can just do this:
DWORD dwTickCount = GetTickCount();
// Perform some things.
printf("Code took: %dms\n", GetTickCount() - dwTickCount);
Not the most general/elegant solution, but nice and quick when you need it.

How can I get the current time in milliseconds using C?

How might I get the current time in milliseconds in C? I am doing following to get the time in seconds:
struct tm ptm;
now = time(NULL);
localtime_r(&now,ptm);
myTime= (ptm->tm_hour * 3600) + (ptm->tm_min * 60) + (ptm->tm_sec);
Looking at time.h, struct tm does not have the millisecond member in it.
On Unix, use gettimeofday() to get the answer in microseconds and scale to milliseconds.
Or use POSIX clock_gettime() to get the answer in nanoseconds and scale to milliseconds.
I use ftime for time tracking (link text)

Resources