get the current time in seconds
I am wondering is there any function that would return the current time in seconds, just 2 digits of seconds? I'm using gcc 开发者_如何学Go4.4.2.
The following complete program shows you how to access the seconds value:
#include <stdio.h>
#include <time.h>
int main (int argc, char *argv[]) {
time_t now;
struct tm *tm;
now = time(0);
if ((tm = localtime (&now)) == NULL) {
printf ("Error extracting time stuff\n");
return 1;
}
printf ("%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);
return 0;
}
It outputs:
2010-02-11 15:58:29
How it works is as follows.
- it calls
time()
to get the best approximation to the current time (usually number of seconds since the epoch but that's not actually mandated by the standard). - it then calls
localtime()
to convert that to a structure which contains the individual date and time fields, among other things. - at that point, you can just de-reference the structure to get the fields you're interested in (
tm_sec
in your case but I've shown a few of them).
Keep in mind you can also use gmtime()
instead of localtime()
if you want Greenwich time, or UTC for those too young to remember :-).
A more portable way to do this is to get the current time as a time_t
struct:
time_t mytime = time((time_t*)0);
Retrieve a struct tm
for this time_t
:
struct tm *mytm = localtime(&mytime);
Examine the tm_sec
member of mytm
. Depending on your C library, there's no guarantee that the return value of time()
is based on a number of seconds since the start of a minute.
You can get the current time with gettimeofday
(C11), time
(Linux), or localtime_r
(POSIX); depending on what calendar & epoch you're interested. You can convert it to seconds elapsed after calendar epoch, or seconds of current minute, whichever you are after:
#include <stdio.h>
#include <string.h>
#include <time.h>
int main() {
time_t current_secs = time(NULL);
localtime_r(¤t_secs, ¤t_time);
char secstr[128] = {};
struct tm current_time;
strftime(secstr, sizeof secstr, "%S", ¤t_time);
fprintf(stdout, "The second: %s\n", secstr);
return 0;
}
You want to use gettimeofday:
man 2 gettimeofday
#include <stdio.h>
#include <sys/time.h>
int main (int argc, char **argv)
{
int iRet;
struct timeval tv;
iRet = gettimeofday (&tv, NULL); // timezone structure is obsolete
if (iRet == 0)
{
printf ("Seconds/USeconds since epoch: %d/%d\n",
(int)tv.tv_sec, (int)tv.tv_usec);
return 0;
}
else
{
perror ("gettimeofday");
}
return iRet;
}
This is better to use then time(0), because you get the useconds as well, atomically, which is the more common use case.
精彩评论