C: How to get system timestamp (in second, millisecond, and microsecond)?

This tutorial may not apply to Windows.

The online c++ reference gives information on how to get system time.  However, the time returned has a resolution of only one second.  Here is an example code of how to get system time with resolution of one millisecond and one microsecond.

  • Code:
/* timestamp example */
#include <stdio.h>      /* printf */
#include <time.h>       /* time_t, time (for timestamp in second) */
#include <sys/timeb.h>  /* ftime, timeb (for timestamp in millisecond) */
#include <sys/time.h>   /* gettimeofday, timeval (for timestamp in microsecond) */

int main ()
  /* Example of timestamp in second. */
  time_t timestamp_sec; /* timestamp in second */
  time(&timestamp_sec);  /* get current time; same as: timestamp_sec = time(NULL)  */
  printf ("%ld seconds since epoch\n", timestamp_sec);

  /* Example of timestamp in millisecond. */
  struct timeb timer_msec;
  long long int timestamp_msec; /* timestamp in millisecond. */
  if (!ftime(&timer_msec)) {
  	timestamp_msec = ((long long int) timer_msec.time) * 1000ll + 
  						(long long int) timer_msec.millitm;
  else {
  	timestamp_msec = -1;
  printf("%lld milliseconds since epoch\n", timestamp_msec);

  /* Example of timestamp in microsecond. */
  struct timeval timer_usec; 
  long long int timestamp_usec; /* timestamp in microsecond */
  if (!gettimeofday(&timer_usec, NULL)) {
  	timestamp_usec = ((long long int) timer_usec.tv_sec) * 1000000ll + 
  						(long long int) timer_usec.tv_usec;
  else {
  	timestamp_usec = -1;
  printf("%lld microseconds since epoch\n", timestamp_usec);

  printf("epoch is 00:00 hours, Jan 1, 1970 UTC\n");

  return 0;

compile and run:

gcc timestamp.c -o timestamp

example result (numbers are  different from yours):

1415500887 seconds since epoch
1415500887236 milliseconds since epoch
1415500887236779 microseconds since epoch
epoch is 00:00 hours, Jan 1, 1970 UTC
  • Reference:

c++ reference on function “time” in “time.h”.

information on struct “timeval” and function “gettimeofday” in “sys/time.h”.

information on struct “timeb” and function “ftime” in “sys/timeb.h”.

another tutorial on system time (with much more information.)

  •  Note:

time_t is an alias of type long.

The c++ reference doesn’t really say what the actual data type “time_t” is.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s