Categories
Coding

How to Get Timestamp in C

To get a timestamp in C you can use functions from the <time.h> library.

Using time()

This gives you the number of seconds since the Unix epoch (January 1, 1970).

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

int main() {
time_t timestamp = time(NULL);
printf("Timestamp: %ld\n", timestamp);
return 0;
}

Using gettimeofday()

This gives microsecond precision.

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

int main() {
struct timeval tv;
gettimeofday(&tv, NULL);
printf("Seconds: %ld\n", tv.tv_sec);
printf("Microseconds: %ld\n", tv.tv_usec);
return 0;
}

Using clock_gettime()

This gives nanosecond precision and different clock types.

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

int main() {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
printf("Seconds: %ld\n", ts.tv_sec);
printf("Nanoseconds: %ld\n", ts.tv_nsec);
return 0;
}

Formatted Timestamp

To get a human readable timestamp:

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

int main() {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char timestamp[64];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", tm);
printf("Formatted timestamp: %s\n", timestamp);
return 0;
}

High Resolution Timer (Windows Specific)

For Windows you can use QueryPerformanceCounter():

#include <windows.h>
#include <stdio.h>

int main() {
LARGE_INTEGER frequency, start;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
printf("Timestamp: %lld\n", start.QuadPart);
return 0;
}

To link with the proper libraries when compiling. For example on Unix systems you will need to use -lrt for clock_gettime().

Each method has its use cases

  • time() is simple but only provides second level precision.
  • gettimeofday() is highly supported and offers microsecond precision.
  • clock_gettime() is more modern and flexible and comes with nanosecond precision.
  • Formatted timestamps are useful for logging and human readable output.
  • QueryPerformanceCounter() is specific to Windows and provides high resolution timing.

Leave a Reply

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