Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

GNU date(1) understands the %N format spec, which outputs nanoseconds, so:

$ date +%H:%M:%S.%N

outputs 19:10:03.725196000

BSD date doesn't understand %N. How can I print the current time with sub-second precision on OS X?

share|improve this question
up vote 5 down vote accepted

If you have a modern-enough Perl interpreter handy (Time::HiRes is bundled since 5.7.2), you could use some variation of this:

#!/usr/bin/env perl
use strict;
use warnings;

use Time::HiRes qw(gettimeofday);
use POSIX       qw(strftime);

my ($s,$us) = gettimeofday();
printf "%s.%06d\n", strftime("%H:%M:%S", localtime($s)), $us;

Sample output:

$ ./t.pl 

If you don't have perl (or don't want to use it), but you do have a C compiler, you could use this:

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

int main(void)
    struct timeval now;
    struct tm *tmp;
    char timestr[9];
    int rc;

    rc = gettimeofday(&now, 0);
    if (rc != 0) {
        return 1;

    tmp = localtime(&now.tv_sec);
    if (tmp == 0) {
        return 1;

    rc = strftime(timestr, sizeof(timestr), "%H:%M:%S", tmp);
    if (rc == 0) {
        fprintf(stderr, "strftime call failed.\n");
        return 1;
    printf("%s.%06ld\n", timestr, now.tv_usec);
    return 0;
share|improve this answer
On a side note: (I know very little about Perl)... I was curious about the speed of interpreted Perl vs the c executable... As expected the c executable was much faster to load/run.. (approx 16 times faster, over 100 consecutive itterations)... So, to be fair to Perl, I compiled the Perl script using pp (from libpar-packer-perl)... To my surprise, this perl executable was 11 times slower than the interpreted Perl script (ie, 170 times slower than the c executable)... Is this normal for compiled perl? .. – Peter.O Nov 2 '11 at 5:57
pp packs the complete perl executable, library and dependencies in a single, compressed archive. If the script is short-lived, loading all that and decompressing is going to have a huge overhead compared to how efficient your OS is about caching frequently used code (and loading only the parts that are actually used). I don't know of a reason why pp would run the code faster either once loaded. – Mat Nov 2 '11 at 6:34
@Mat: Thanks. It makes sense now :) – Peter.O Nov 2 '11 at 6:56
I ended adopting the C version for the least overhead, thank you – Daniel Serodio Nov 5 '11 at 3:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.