Epoch in Chapel

Here’s the translated code and explanation in Chapel, formatted for Hugo:

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 Chapel.

use Time;

proc main() {
    // Use Time.getCurrentTime() to get the current time
    var now = Time.getCurrentTime();
    writeln(now);

    // Get seconds since the Unix epoch
    var secondsSinceEpoch = now.unix();
    writeln(secondsSinceEpoch);

    // Get milliseconds since the Unix epoch
    var millisSinceEpoch = now.unix() * 1000 + now.microseconds() / 1000;
    writeln(millisSinceEpoch);

    // Get nanoseconds since the Unix epoch
    var nanosSinceEpoch = now.unix() * 1_000_000_000 + now.microseconds() * 1000;
    writeln(nanosSinceEpoch);

    // Convert seconds since epoch back to a time
    var timeFromSeconds = Time.timeSinceEpoch(secondsSinceEpoch: real);
    writeln(timeFromSeconds);

    // Convert nanoseconds since epoch back to a time
    var timeFromNanos = Time.timeSinceEpoch(nanosSinceEpoch: real / 1_000_000_000);
    writeln(timeFromNanos);
}

To run the program:

$ chpl epoch.chpl
$ ./epoch
2023-06-08T12:34:56.789-04:00
1686239696
1686239696789
1686239696789000000
2023-06-08T12:34:56.000-04:00
2023-06-08T12:34:56.789-04:00

In Chapel, we use the Time module to work with time-related functions. The getCurrentTime() method returns the current time. We can then use various methods to get the time in different formats:

  • unix() returns the number of seconds since the Unix epoch.
  • To get milliseconds and nanoseconds, we need to do some calculations using unix() and microseconds() methods.
  • To convert back from seconds or nanoseconds to a time object, we use the timeSinceEpoch() function.

Note that Chapel doesn’t have built-in methods for milliseconds and nanoseconds since the epoch, so we calculate these manually. The precision might be slightly different from other languages due to these calculations.

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