What is the most efficient way of getting current time/date/day/year in C language? As I have to execute this many times, I need a real efficient way. I am on freeBSD.
thanks in advance.
What is the most efficient way of getting current time/date/day/year in C language? As I have to execute this many times, I need a real efficient way. I am on freeBSD.
thanks in advance.
The simplest is
#include <time.h>
//...
time_t current_time = time (NULL);
struct tm* local_time = localtime (¤t_time);
printf ("the time is %s\n", asctime (local_time));
It really depends on what you mean by "many" :-)
I think you'll probably find that using the ISO standard time()
and localtime()
functions will be more than fast enough.
The time()
function gives you the number of seconds since the epoch, while localtime()
both converts it to local time (from UTC) and splits it into a more usable form, the struct tm
structure.
#include <time.h>
time_t t = time (NULL);
struct tm* lt = localtime (&t);
// Use lt->tm_year, lt->tm_mday, and so forth.
Any attempt to cache the date/time and use other ways of finding out a delta to apply to it, such as with clock()
, will almost invariably:
Just about the only way (that's standard, anyway) is to call time
followed by localtime
or gmtime
.
well, in general, directly accessing the OS's API to get the time is probably the most efficient, but not so portable.....
the C time functions are ok.
But really depends on your platform
/* ctime example */
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
time ( &rawtime );
printf ( "The current local time is: %s", ctime (&rawtime) );
return 0;
}
You can use ctime, if you need it as a string.
Standard C provides only one way to get the time - time()
- which can be converted to a time/date/year with localtime()
or gmtime()
. So by definition, that must be the most efficient way.
Any other methods are operating-system specific, and you haven't told us what operating system you're using.
You can use gettimeofday() function to get time in seconds & microseconds which is (I think) very fast (as there is a similar function in Linux kernel do_gettimeofday()) and then you can convert it to your required format (might possible to use functions mentioned above for conversion.
I hope this helps.