Getting Duration - c

I'm trying to measure duration of something.
when it start I call start_time = time(NULL);
when it ends:
time_t a_time = time(NULL) - start_time;
struct tm * ts = localtime(&a_time);
char time_buff[32];
memset (time_buff,0,32);
sprintf (time_buff, "Duration: %02d:%02d:%02d", ts->tm_hour, ts->tm_min, ts->tm_sec);
The problem is that ts->tm_hour is always 2.
Please advise.
Thanks,
Nahum

The function localtime converts the time to a complete date and time. You better convert it to days, hours and minutes yourself though divisions and modulo operations.

do you eventualy live in a country where the time is 2 hours away from UTC time ?
replace your call to localtime() (which is in your current timezone) by a call to gmtime().

Why not use a function that returns the amount of milliseconds elapsed (clock or gettimeofday) and then convert to hour/min/sec?

Related

Getting UTC time as time_t

I am trying to get UTC time as time_t.
Code below seems giving it correct but surprisingly prints local time only:
time_t mytime;
struct tm * ptm;
time ( &mytime ); // Get local time in time_t
ptm = gmtime ( &mytime ); // Find out UTC time
time_t utctime = mktime(ptm); // Get UTC time as time_t
printf("\nLocal time %X (%s) and UTC Time %X (%s)", mytime, ctime(&mytime), utctime, ctime(&utctime));
As we can see values of mytime and utctime we get are different.
However, when passed as parameters to ctime it converts them to same string.
Local time 55D0CB59 (Sun Aug 16 23:11:45 2015) and UTC Time 55D07E01
(Sun Aug 16 23:11:45 2015)
By definition the C time() function returns a time_t epoch time in UTC. So the code commented "//get the local time in time_t" is really getting UTC already, and the comment is incorrect.
From the Linux man-page:
time_t time(time_t *tloc);
time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
Giving the code:
#include <time.h>
...
time_t utc_now = time( NULL );
The ctime result is a static variable. Do not use ctime twice in the same print statement. Do it in two separate print statements.
If ctime is replaced with asctime, the same problem will arise as asctime also returns the result as a static variable.
That's exactly what the documented behavior is supposed to do:
Interprets the value pointed by timer as a calendar time and converts it to a C-string containing a human-readable version of the corresponding time and date, in terms of local time.
You probably want to use asctime instead.
ctime function returns a C string containing the date and time information in a human-readable format.
To get time in UTC you can use gettimeofday() (for Linux)-
struct timeval ptm;
gettimeofday(&ptm,NULL);
long int ms = ptm.tv_sec * 1000 + ptm.tv_usec / 1000;
And you can see function GetSystemTime in for windows.

How to format system time in C?

I'm working on an element of a program that fetches the system time in (24 hour time) hours and minutes, and formats it as HH:MM and stores it in an array. The minutes also have to be incremented by 1. This is my code:
strftime (timeh,10,"%H:",formtime);
strftime (timem,10,"%M",formtime);
timem1 = atoi(timem);
++timem1;
itoa(timem1, timem, 10);
strcpy(time, timeh);
strcat(time, timem);
I tested it by simply having it print out time, and this was the output of printf("%s", time):
5. (the time was 1:04 AM)
Individually, the hours print as nothing (at 1:08 AM), and the minutes print correctly.
What can I do to make the array time hold the properly formatted HH:MM time?
Thanks for all your suggestions
If I read you question right, you should be able to do it with:
formtime->tm_min++; /* Additional checks needed. */
strftime(time, 10, "%H:%M", formtime);
Rather than trying to adjust the minutes directly and having to worry about wrapping at the hour, you should adjust the time by 60 seconds before splitting it into a struct tm for formatting:
time_t now;
time(&now);
now += 60;
strftime(buffer, sizeof(buffer), "%H:%M", localtime(&now));
Note that calling your array time is not a good idea, as that will conflict with the standard function time used to get the current time.

a time function in C linux

hi i was wondering if it is possible to edit the time function.for my program to give a time for a user to retry again?
struct tm * abc()
{
char *time_string;
time_t curtime;
struct tm *loctime;
/* Get the current time. */
curtime = time (NULL);
/* Convert it to local time representation. */
loctime = localtime (&curtime);
return loctime;
}
this will return the current time but want i want to do is to edit this to add a value. The reason for me doing this is so i can tell a user to try again at a certain time using the current and adding 2minutes to it. Not sure if this is the correct way?
Thanks
time() returns a timestamp in seconds (number of seconds since the epoch), so you can just add the required delay.
curtime = time (NULL) + 2*60; // Adds two minutes,
Add the following lines just before the return.
localtime->tm_min += 2;
mktime(localtime);
The first line adds two minutes to localtime.
The second line renormalizes localtime to a "standard" format, in other words you it will roll the added minutes from values like (61) to values like (hours+1),(minutes = 1).

How to get current hour (time of day) in linux kernel space

I'm writing a kernel module that checks to see if the time is between two specified hours, and disables input if it is. This has to do with me wanting to make sure I go to bed early. (I know I could also use any number of different techniques including cron etc, but I wanted to learn kernel programming...)
As a first version, I therefore check if the current hour is between start and end, which are set via parameters to the module.
My question is therefore : How do I get the current hour? I have no access to the usual time functions in the standard library because I am in kernel space. I'm guessing that I should be using do_gettimeofday() for this, but that only gives me seconds and nanoseconds, and I need hours in the current day.
Thanks.
time_to_tm function can be of your help, which returns the structure tm. Timezone available in variable sys_tz, it can help you to set your offset properly to get local time.
To get the local time in kernel, add the below code snippet your kernel driver:
struct timeval time;
unsigned long local_time;
do_gettimeofday(&time);
local_time = (u32)(time.tv_sec - (sys_tz.tz_minuteswest * 60));
rtc_time_to_tm(local_time, &tm);
printk(" # (%04d-%02d-%02d %02d:%02d:%02d)\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
This works well for me:
#include <linux/time.h>
...
/* getnstimeofday - Returns the time of day in a timespec */
void getnstimeofday(struct timespec *ts)
For getting usual time format you can use:
printk("TIME: %.2lu:%.2lu:%.2lu:%.6lu \r\n",
(curr_tm.tv_sec / 3600) % (24),
(curr_tm.tv_sec / 60) % (60),
curr_tm.tv_sec % 60,
curr_tm.tv_nsec / 1000);
Converting the do_gettimeofday result to an hour is pretty simple, since it starts at midnight GMT.
time_t t = time(0);
time_t SecondsOfDay = t % (24*60*60);
time_t HourGMT = SecondsOfDay / (60*60);
Then adjust for your local timezone
We can use clock_gettime function with CLOCK_REALTIME as the type of clock.
Reference http://linux.die.net/man/3/clock_gettime
Just doing a strace on date executable gives us an idea to get the current date in the kernel mode.

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