Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

1 Answer 1

up vote 3 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 
19:52:35.408520

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) {
        perror("gettimeofday");
        return 1;
    }

    tmp = localtime(&now.tv_sec);
    if (tmp == 0) {
        perror("localtime");
        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
1  
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

 
discard

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.