Epoch in Cilk

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Cilk.

#include <cilk/cilk.h>
#include <iostream>
#include <chrono>

int main() {
    // Use std::chrono::system_clock to get the current time
    auto now = std::chrono::system_clock::now();
    std::cout << now.time_since_epoch().count() << std::endl;

    // Get elapsed time since the Unix epoch in seconds
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
    std::cout << seconds.count() << std::endl;

    // Get elapsed time since the Unix epoch in milliseconds
    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
    std::cout << milliseconds.count() << std::endl;

    // Get elapsed time since the Unix epoch in nanoseconds
    auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch());
    std::cout << nanoseconds.count() << std::endl;

    // Convert integer seconds since the epoch into the corresponding time_point
    auto time_point_sec = std::chrono::system_clock::time_point(std::chrono::seconds(seconds.count()));
    std::cout << time_point_sec.time_since_epoch().count() << std::endl;

    // Convert integer nanoseconds since the epoch into the corresponding time_point
    auto time_point_nano = std::chrono::system_clock::time_point(std::chrono::nanoseconds(nanoseconds.count()));
    std::cout << time_point_nano.time_since_epoch().count() << std::endl;

    return 0;
}

In this Cilk program, we use the std::chrono library to work with time. The std::chrono::system_clock::now() function is used to get the current time.

We can then use duration_cast to convert the time to seconds, milliseconds, or nanoseconds since the Unix epoch.

To convert integer seconds or nanoseconds since the epoch into the corresponding time point, we can create a std::chrono::system_clock::time_point with the desired duration.

When you compile and run this program, you’ll see output similar to this:

1638360000000000000
1638360000
1638360000000
1638360000000000000
1638360000000000000
1638360000000000000

The exact numbers will depend on when you run the program.

Next, we’ll look at another time-related task: time parsing and formatting.