View Full Version : How can I get system time with milliseconds in C

January 3rd, 2009, 05:19 PM
I'm an Electronics and Communication engineering student but extremely interested in programming.

I'm trying to develop a software tool to encrypt files using TDMRC algorithm. This algorithm requires the current system time to generate a random seed. I need some method(Standard library function or some other) to get the system time with the following fields.


No problem with the first three fields. But I'm not able to get the millisecond part.

Someone please help me. I'm writing the program in C.

January 3rd, 2009, 05:24 PM
Use gettimeofday(). Read the man-page for such. You will note that it returns time down to the microsecond level; just perform a basic arithmetic operation to calculate milliseconds.

struct timeval tv;

gettimeofday(&tv, 0);


January 3rd, 2009, 05:33 PM
Thank you very much for spending time for me.
Which header file should I use?
How can I get more information about this function from the bash shell?

Actually I'm a beginner to the world of linux.

January 3rd, 2009, 05:37 PM
Header file:

#include <sys/time.h>

From the shell:

man gettimeofday

If you do not have the man-pages installed:

sudo apt-get install manpages-dev

January 3rd, 2009, 11:36 PM
Time of day isn't a very good source of randomness. A program may be run by cron or another scheduling mechanism. That would make the time values not very random at all.

You can read from /dev/random on a linux system to get high quality random numbers. See "man urandom" for details on the /dev/random and /dev/urandom pseudodevices.

January 4th, 2009, 04:17 AM
I just happen to be working on a similar problem. Check out this link.... http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_19.html

It has what dwhitney said but with all the bells and whistles.