How to use the time() function in C/C++?

Filed Under: C Programming
Time C Cpp

In this article, we’ll take a look at using the time() function in C/C++.

The time() function is a useful utility function that we can use to measure the elapsed time of our program.

Let’s look at how we can use this function, using some simple examples!


Basic Syntax of the time() function in C/C++

This function belongs to the header file <time.h>, so we must include this before calling time().

#include <time.h>
time_t time(time_t *tloc);

This takes in a pointer to a time_t datatype and returns the time elapsed since 00:00:00 UTC, January 1, 1970.

The time value returned is in seconds, so you must make suitable conversions from it.

If tloc is not a null pointer, the returned value is also stored in the object pointed to by second.

Otherwise, if tloc is NULL, the return value is not stored anywhere.

Let’s look at some simple examples now.

Using time() in C/C++ – Some Examples

Let’s first look at the case when tloc is a NULL pointer.

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

int main() {
    time_t num_seconds = time(NULL); // Passing NULL to time()
    printf("Since 1st January 1970 UTC, No. of seconds = %d, No. of days = %d", (int)num_seconds, (int)num_seconds/86400);
    return 0;
}

Output

Since 1st January 1970 UTC, No. of seconds = 1592317455, No. of days = 18429

As of the time of writing (June 16 2020), this is indeed true!

Now, let’s go to the second case, when tloc is not NULL.

In this case, since the return value will be stored to the pointer location, there is no need to assign it separately!

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

int main() {
    time_t tloc;
    time(&tloc); // Storing the return value to tloc
    printf("Since 1st January 1970 UTC, No. of seconds = %d, No. of days = %d", (int)tloc, (int)tloc/86400);
    return 0;
}

This will give a similar output as before.


Conclusion

In this article, we learned about using the time() function in C / C++, to get the time elapsed since the first epoch.

For more content on C and C++, do go through our tutorial section on C programming!

References


Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages