Convert milliseconds to timespec for GNU port - c

I want to convert milliseconds into timespec structure used by GNU Linux. I have tried following code for the same.
timespec GetTimeSpecValue(unsigned long milisec)
{
struct timespec req;
//long sec = (milisecondtime /1000);
time_t sec = (time_t)(milisec/1000);
req->tv_sec = sec;
req->tv_nsec = 0;
return req;
}
Running this code gives me the following error.
expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘GetTimeSpecValue’
I have also include time.h file in the code.

The timespec structure represents time in two portions — seconds and nanoseconds. Thus, the algorithm for conversion from milliseconds is pretty darn simple. One seconds has thousand milliseconds, one milliseconds has a thousand microseconds and one microsecond has a thousand nanoseconds, for which we are grateful to SI. Therefore, we first need to divide milliseconds by a thousand to get a number of seconds. Say, for example, 1500 milliseconds / 1000 = 1.5 seconds. Given integer arithmetics (not a floating point), the remainder is dropped (i.e. 1500 / 1000 is equal to just 1, not 1.5). Then we need to take a remainder that denotes a number of milliseconds that is definitely less than one second, and multiply it by a million to convert it to nanoseconds. To get a remainder of dividing by 1000, we use a module operator (%) (i.e. 1500 % 1000 is equal to 500). For example, let's convert 4321 milliseconds to seconds and nanoseconds:
4321 (milliseconds) / 1000 = 4 (seconds)
4321 (milliseconds) % 1000 = 321 (milliseconds)
321 (milliseconds) * 1000000 = 321000000 (nanoseconds)
Knowing the above, the only thing that is left is to write a little bit of C code. There are few things that you didn't get right:
In C, you have to prefix structure data types with struct. For example, instead of saying timespec you say struct timespec. In C++, however, you don't have to do it (unfortunately, in my opinion).
You cannot return structures from the function in C. Therefore, you need to pass a structure by pointer into a function that does something with that structure.
Edit: This contradicts (Return a `struct` from a function in C).
OK, enough talking. Below is a simple C code example:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
static void ms2ts(struct timespec *ts, unsigned long ms)
{
ts->tv_sec = ms / 1000;
ts->tv_nsec = (ms % 1000) * 1000000;
}
static void print_ts(unsigned long ms)
{
struct timespec ts;
ms2ts(&ts, ms);
printf("%lu milliseconds is %ld seconds and %ld nanoseconds.\n",
ms, ts.tv_sec, ts.tv_nsec);
}
int main()
{
print_ts(1000);
print_ts(2500);
print_ts(4321);
return EXIT_SUCCESS;
}
Hope it helps. Good Luck!

try this:
struct timespec GetTimeSpecValue(unsigned long millisec) {
struct timespec req;
req.tv_sec= (time_t)(millisec/1000);
req.tv_nsec = (millisec % 1000) * 1000000;
return req;
}
I don't think struct timespec is typedef'ed,hence you need to prepend timespec with struct. And work out the nano second part if you want to be precise. Note that req is not a pointer. Thus members cannot be accessed with '->'

Incorporating a few tweaks to the answer including Geoffrey's comment, the code below avoids divides for small delay and modulo for long delay:
void msec_to_timespec(unsigned long msec, struct timespec *ts)
{
if (msec < 1000){
ts->tv_sec = 0;
ts->tv_nsec = msec * 1000000;
}
else {
ts->tv_sec = msec / 1000;
ts->tv_nsec = (msec - ts->tv_sec * 1000) * 1000000;
}
}

Related

Measuring Elapsed Time Using clock_gettime(CLOCK_MONOTONIC)

I have to elapse the measuring time during multiple threads. I must get an output like this:
Starting Time | Thread Number
00000000000 | 1
00000000100 | 2
00000000200 | 3
Firstly, I used gettimeofday but I saw that there are some negative numbers then I made little research and learn that gettimeofday is not reliable to measure elapsed time. Then I decide to use clock_gettime(CLOCK_MONOTONIC).
However, there is a problem. When I use second to measure time, I cannot measure time precisely. When I use nanosecond, length of end.tv_nsec variable cannot exceed 9 digits (since it is a long variable). That means, when it has to move to the 10th digit, it still remains at 9 digits and actually the number gets smaller, causing the elapsed time to be negative.
That is my code:
long elapsedTime;
struct timespec end;
struct timespec start2;
//gettimeofday(&start2, NULL);
clock_gettime(CLOCK_MONOTONIC,&start2);
while(c <= totalCount)
{
if(strcmp(algorithm,"FCFS") == 0)
{
printf("In SErunner count=%d \n",count);
if(count > 0)
{
printf("Count = %d \n",count);
it = deQueue();
c++;
tid = it->tid;
clock_gettime(CLOCK_MONOTONIC,&end);
usleep( 1000*(it->value));
elapsedTime = ( end.tv_sec - start2.tv_sec);
printf("Process of thread %d finished with value %d\n",it->tid,it->value);
fprintf(outputFile,"%ld %d %d\n",elapsedTime,it->value,it->tid+1);
}
}
Unfortunately, timespec does not have microsecond variable. If you can help me I will be very happy.
Write a helper function that calculates the difference between two timespecs:
int64_t difftimespec_ns(const struct timespec after, const struct timespec before)
{
return ((int64_t)after.tv_sec - (int64_t)before.tv_sec) * (int64_t)1000000000
+ ((int64_t)after.tv_nsec - (int64_t)before.tv_nsec);
}
If you want it in microseconds, just divide it by 1000, or use:
int64_t difftimespec_us(const struct timespec after, const struct timespec before)
{
return ((int64_t)after.tv_sec - (int64_t)before.tv_sec) * (int64_t)1000000
+ ((int64_t)after.tv_nsec - (int64_t)before.tv_nsec) / 1000;
}
Remember to include <inttypes.h>, so that you can use conversion "%" PRIi64 to print integers of int64_t type:
printf("%09" PRIi64 " | 5\n", difftimespec_ns(after, before));
To calculate the delta (elapsed time), you need to make an substraction between two timeval or two timespec structures depending on the services you are using.
For timeval, there is a set of operations to manipulate struct timeval in <sys/time.h> (e.g. /usr/include/x86_64-linux-gnu/sys/time.h):
# define timersub(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
(result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
if ((result)->tv_usec < 0) { \
--(result)->tv_sec; \
(result)->tv_usec += 1000000; \
} \
} while (0)
For timespec, if you don't have them installed in your header files, copy something like the macro defined in this source code:
#define timespecsub(tsp, usp, vsp) \
do { \
(vsp)->tv_sec = (tsp)->tv_sec - (usp)->tv_sec; \
(vsp)->tv_nsec = (tsp)->tv_nsec - (usp)->tv_nsec; \
if ((vsp)->tv_nsec < 0) { \
(vsp)->tv_sec--; \
(vsp)->tv_nsec += 1000000000L; \
} \
} while (0)
You could convert the time to a double value using some code such as :
double
clocktime_BM (clockid_t clid)
{
struct timespec ts = { 0, 0 };
if (clock_gettime (clid, &ts))
return NAN;
return (double) ts.tv_sec + 1.0e-9 * ts.tv_nsec;
}
The returned double value contains something in seconds. On most machines, double-s are IEEE 754 floating point numbers, and basic operations on them are fast (less than a µs each). Read the floating-point-gui.de for more about them. In 2020 x86-64 based laptops and servers have some HPET. Don't expect a microsecond precision on time measurements (since Linux runs many processes, and they might get scheduled at arbitrary times; read some good textbook about operating systems for explanations).
(the above code is from Bismon, funded thru CHARIOT; something similar appears in RefPerSys)
On Linux, be sure to read syscalls(2), clock_gettime(2), errno(3), time(7), vdso(7).
Consider studying the source code of the Linux kernel and/or of the GNU libc and/or of musl-libc. See LinuxFromScratch and OSDEV and kernelnewbies.
Be aware of The year 2038 problem on some 32 bits computers.

gettimeofday for displaying current time without using space

Is there any way to store number of time ticks from gettimeofday() and format into some specific way (for example "%m-%d-%Y %T") without using any array?.
This will save memory for each instance of a program which calculates current time.
Code for the same using an array.(Taken from C - gettimeofday for computing time?)
char buffer[30];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
curtime=tv.tv_sec;
strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime));
printf("%s%ld\n",buffer,tv.tv_usec);
any way to store number ... from gettimeofday() and ... without using any array?
gettimeofday() does not return the "number of time ticks". It is a *nix functions defined to populate a struct timeval which contains a time_t and a long representing the current time in seconds and microseconds. Use clock() to get "number of time ticks".
The simplest way to avoid an array is to keep the result in a struct timeval without any modifications.
This will save memory for each instance of a program which calculates current time.
This sounds like OP would like to conserve memory as much as possible. Code could convert the struct timeval to a int64_t (a count of microseconds since the epoch) without much risk of range loss. This would only be a memory savings if sizeof(struct timeval) > sizeof(int64_t).
#include <sys/time.h>
int64_t timeval_to_int64(const struct timeval *tv) {
const int32_t us_per_s = 1000000;
int64_t t = tv->tv_sec;
if (t >= INT64_MAX / us_per_s
&& (t > INT64_MAX / us_per_s || tv->tv_usec > INT64_MAX % us_per_s)) {
// Handle overflow
return INT64_MAX;
}
if (t <= INT64_MIN / us_per_s
&& (t < INT64_MIN / us_per_s || tv->tv_usec < INT64_MIN % us_per_s)) {
// Handle underflow
return INT64_MIN;
}
return t * us_per_s + tv->tv_usec;
}
void int64_to_timeval(struct timeval *tv, int64_t t) {
const int32_t us_per_s = 1000000;
tv->tv_sec = t / us_per_s;
tv->tv_usec = t % us_per_s;
if (tv->tv_usec < 0) { // insure tv_usec member is positive.
tv->tv_usec += us_per_s;
tv->tv_sec++;
}
}
If code wants to save the timestamp to a file as text, with minimal space, a number of choices are available. What is the most efficient binary to text encoding?
goes over some ideas. For OP's code though a decimal or hexadecimal print of the 2 members may be sufficient.
printf("%lld.%06ld\n", (long long) tv.tv_sec, tv.tv_usec);
I do not recommend storing timestamps via localtime() as that imparts ambiguity or overhead of timezone and day light savings time. If code must saving using month, day, year, consider ISO 8601 and using universal time.
#include <sys/time.h>
int print_timeval_to_ISO8601(const struct timeval *tv) {
struct tm t = *gmtime(&tv->tv_sec);
return printf("%04d-%02d-%02dT%02d:%02d:%02d.%06ld\n", //
t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, //
t.tm_hour, t.tm_min, t.tm_sec, tv->tv_usec);
// Or ("%04d%02d%02d%02d%02d%02d.%06ld\n"
}
Note OP's code has a weakness. Microsecond values like 12 will print a ".12" when ".000012" should appear.
// printf("%s%ld\n",buffer,tv.tv_usec);
printf("%s%06ld\n",buffer,tv.tv_usec);

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

clock_gettime on Raspberry Pi with C

I want to measure the time between the start to the end of the function in a loop. This difference will be used to set the amount of loops of the inner while-loops which does some here not important stuff.
I want to time the function like this :
#include <wiringPi.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#define BILLION 1E9
float hz = 1000;
long int nsPerTick = BILLION/hz;
double unprocessed = 1;
struct timespec now;
struct timespec last;
clock_gettime(CLOCK_REALTIME, &last);
[ ... ]
while (1)
{
clock_gettime(CLOCK_REALTIME, &now);
double diff = (last.tv_nsec - now.tv_nsec );
unprocessed = unprocessed + (diff/ nsPerTick);
clock_gettime(CLOCK_REALTIME, &last);
while (unprocessed >= 1) {
unprocessed --;
DO SOME RANDOM MAGIC;
}
}
The difference between the timer is always negative. I was told this was where the error was:
if ( (last.tv_nsec - now.tv_nsec)<0) {
double diff = 1000000000+ last.tv_nsec - now.tv_nsec;
}
else {
double diff = (last.tv_nsec - now.tv_nsec );
}
But still, my variable difference and is always negative like "-1095043244" (but the time spent during the function is a positive of course).
What's wrong?
Your first issue is that you have `last.tv_nsec - now.tv_nsec, which is the wrong way round.
last.tv_nsec is in the past (let's say it's set to 1), and now.tv_nsec will always be later (for example, 8ns later, so it's 9). In that case, last.tv_nsec - now.tv_nsec == 1 - 9 == -8.
The other issue is that tv_nsec isn't the time in nanoseconds: for that, you'd need to multiply the time in seconds by a billion and add that. So to get the difference in ns between now and last, you want:
((now.tv_sec - last.tv_sec) * ONE_BILLION) + (now.tv_nsec - last.tv_nsec)
(N.B. I'm still a little surprised that although now.tv_nsec and last.tv_nsec are both less than a billion, subtracting one from the other gives a value less than -1000000000, so there may yet be something I'm missing here.)
I was just investigating timing on Pi, with similar approach and similar problems. My thoughts are:
You don't have to use double. In fact you also don't need nano-seconds, as the clock on Pi has 1 microsecond accuracy anyway (it's the way the Broadcom did it). I suggest you to use gettimeofday() to get microsecs instead of nanosecs. Then computation is easy, it's just:
number of seconds + (1000 * 1000 * number of micros)
which you can simply calculate as unsigned int.
I've implemented the convenient API for this:
typedef struct
{
struct timeval startTimeVal;
} TIMER_usecCtx_t;
void TIMER_usecStart(TIMER_usecCtx_t* ctx)
{
gettimeofday(&ctx->startTimeVal, NULL);
}
unsigned int TIMER_usecElapsedUs(TIMER_usecCtx_t* ctx)
{
unsigned int rv;
/* get current time */
struct timeval nowTimeVal;
gettimeofday(&nowTimeVal, NULL);
/* compute diff */
rv = 1000000 * (nowTimeVal.tv_sec - ctx->startTimeVal.tv_sec) + nowTimeVal.tv_usec - ctx->startTimeVal.tv_usec;
return rv;
}
And the usage is:
TIMER_usecCtx_t timer;
TIMER_usecStart(&timer);
while (1)
{
if (TIMER_usecElapsedUs(timer) > yourDelayInMicroseconds)
{
doSomethingHere();
TIMER_usecStart(&timer);
}
}
Also notice the gettime() calls on Pi take almost 1 [us] to complete. So, if you need to call gettime() a lot and need more accuracy, go for some more advanced methods of getting time... I've explained more about it in this short article about Pi get-time calls
Well, I don't know C, but if it's a timing issue on a Raspberry Pi it might have something to do with the lack of an RTC (real time clock) on the chip.
You should not be storing last.tv_nsec - now.tv_nsec in a double.
If you look at the documentation of time.h, you can see that tv_nsec is stored as a long. So you will need something along the lines of:
long diff = end.tv_nsec - begin.tv_nsec
With that being said, only comparing the nanoseconds can go wrong. You also need to look at the number of seconds also. So to convert everything to seconds, you can use this:
long nanosec_diff = end.tv_nsec - begin.tv_nsec;
time_t sec_diff = end.tv_sec - begin.tv_sec; // need <sys/types.h> for time_t
double diff_in_seconds = sec_diff + nanosec_diff / 1000000000.0
Also, make sure you are always subtracting the end time from the start time (or else your time will still be negative).
And there you go!

Time stamp in the C programming language

How do I stamp two times t1 and t2 and get the difference in milliseconds in C?
This will give you the time in seconds + microseconds
#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv,NULL);
tv.tv_sec // seconds
tv.tv_usec // microseconds
Standard C99:
#include <time.h>
time_t t0 = time(0);
// ...
time_t t1 = time(0);
double datetime_diff_ms = difftime(t1, t0) * 1000.;
clock_t c0 = clock();
// ...
clock_t c1 = clock();
double runtime_diff_ms = (c1 - c0) * 1000. / CLOCKS_PER_SEC;
The precision of the types is implementation-defined, ie the datetime difference might only return full seconds.
If you want to find elapsed time, this method will work as long as you don't reboot the computer between the start and end.
In Windows, use GetTickCount(). Here's how:
DWORD dwStart = GetTickCount();
...
... process you want to measure elapsed time for
...
DWORD dwElapsed = GetTickCount() - dwStart;
dwElapsed is now the number of elapsed milliseconds.
In Linux, use clock() and CLOCKS_PER_SEC to do about the same thing.
If you need timestamps that last through reboots or across PCs (which would need quite good syncronization indeed), then use the other methods (gettimeofday()).
Also, in Windows at least you can get much better than standard time resolution. Usually, if you called GetTickCount() in a tight loop, you'd see it jumping by 10-50 each time it changed. That's because of the time quantum used by the Windows thread scheduler. This is more or less the amount of time it gives each thread to run before switching to something else. If you do a:
timeBeginPeriod(1);
at the beginning of your program or process and a:
timeEndPeriod(1);
at the end, then the quantum will change to 1 ms, and you will get much better time resolution on the GetTickCount() call. However, this does make a subtle change to how your entire computer runs processes, so keep that in mind. However, Windows Media Player and many other things do this routinely anyway, so I don't worry too much about it.
I'm sure there's probably some way to do the same in Linux (probably with much better control, or maybe with sub-millisecond quantums) but I haven't needed to do that yet in Linux.
/*
Returns the current time.
*/
char *time_stamp(){
char *timestamp = (char *)malloc(sizeof(char) * 16);
time_t ltime;
ltime=time(NULL);
struct tm *tm;
tm=localtime(&ltime);
sprintf(timestamp,"%04d%02d%02d%02d%02d%02d", tm->tm_year+1900, tm->tm_mon,
tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
return timestamp;
}
int main(){
printf(" Timestamp: %s\n",time_stamp());
return 0;
}
Output: Timestamp: 20110912130940 // 2011 Sep 12 13:09:40
Use #Arkaitz Jimenez's code to get two timevals:
#include <sys/time.h>
//...
struct timeval tv1, tv2, diff;
// get the first time:
gettimeofday(&tv1, NULL);
// do whatever it is you want to time
// ...
// get the second time:
gettimeofday(&tv2, NULL);
// get the difference:
int result = timeval_subtract(&diff, &tv1, &tv2);
// the difference is storid in diff now.
Sample code for timeval_subtract can be found at this web site:
/* Subtract the `struct timeval' values X and Y,
storing the result in RESULT.
Return 1 if the difference is negative, otherwise 0. */
int
timeval_subtract (result, x, y)
struct timeval *result, *x, *y;
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
how about this solution? I didn't see anything like this in my search. I am trying to avoid division and make solution simpler.
struct timeval cur_time1, cur_time2, tdiff;
gettimeofday(&cur_time1,NULL);
sleep(1);
gettimeofday(&cur_time2,NULL);
tdiff.tv_sec = cur_time2.tv_sec - cur_time1.tv_sec;
tdiff.tv_usec = cur_time2.tv_usec + (1000000 - cur_time1.tv_usec);
while(tdiff.tv_usec > 1000000)
{
tdiff.tv_sec++;
tdiff.tv_usec -= 1000000;
printf("updated tdiff tv_sec:%ld tv_usec:%ld\n",tdiff.tv_sec, tdiff.tv_usec);
}
printf("end tdiff tv_sec:%ld tv_usec:%ld\n",tdiff.tv_sec, tdiff.tv_usec);
Also making aware of interactions between clock() and usleep(). usleep() suspends the program, and clock() only measures the time the program is running.
If might be better off to use gettimeofday() as mentioned here
Use gettimeofday() or better clock_gettime()
U can try routines in c time library (time.h). Plus take a look at the clock() in the same lib. It gives the clock ticks since the prog has started. But you can save its value before the operation you want to concentrate on, and then after that operation capture the cliock ticks again and find the difference between then to get the time difference.
#include <sys/time.h>
time_t tm = time(NULL);
char stime[4096];
ctime_r(&tm, stime);
stime[strlen(stime) - 1] = '\0';
printf("%s",stime);
This program clearly shows how to do it. Takes time 1 pauses for 1 second and then takes time 2, the difference between the 2 times should be 1000 milliseconds. So your answer is correct
#include <stdio.h>
#include <time.h>
#include <unistd.h>
// Name: miliseconds.c
// gcc /tmp/miliseconds.c -o miliseconds
struct timespec ts1, ts2; // time1 and time2
int main (void) {
// get time1
clock_gettime(CLOCK_REALTIME, &ts1);
sleep(1); // 1 second pause
// get time2
clock_gettime(CLOCK_REALTIME, &ts2);
// nanoseconds difference in mili
long miliseconds1= (ts2.tv_nsec - ts1.tv_nsec) / 10000000 ;
// seconds difference in mili
long miliseconds2 = (ts2.tv_sec - ts1.tv_sec)*1000;
long miliseconds = miliseconds1 + miliseconds2;
printf("%ld\n", miliseconds);
return 0;
}

Resources