C: Printing Current System Time

Posted by Joys of Programming on in C/C++

There are multiple functions using which you can get the current system time in seconds like gettimeofday().But usage of clock_gettime() is recommended. clock_gettime() returns the number of seconds and nano seconds since the Epoch (January 1, 1970). It’s syntax is


int clock_gettime(clockid_t clk_id, struct timespec *tp);

where clk_id can take values like CLOCK_REALTIME (which we will use in the current program to get the current time)

We also make use of the function ctime() in order to print the time in human readable format


#include <time.h>
#include <stdio.h>

void printCurrentTime(){
 struct timespec tp;
 clock_gettime(CLOCK_REALTIME, &tp);
 printf("%s",ctime(&tp.tv_sec));
}

int main(){
 printCurrentTime();
}

Now to compile this program PrintTime.c


$ gcc PrintTime.c -lrt

Note the usage of -lrt. This is used to link the real time libraries.


$ ./a.out

Fri Mar 19 02:53:47 2010


Tags: , , , ,

Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2009-2012 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.8.1 theme from BuyNowShop.com.