Reputation: 1912
I need to convert a time to nanoseconds, the bsd date command isn't suitable, as the best it can returns are seconds.. date +"%H:%M:%S"
returns 17:33:07
..
Seems there is a difference between Mac's BSD date version, and the Linux GNU one. The last one can return nanoseconds. The first can't..
Should I be using python or ruby scripts instead of shell? Or is there another solution to get my nanoseconds on a Mac?
no in fact no %N
Upvotes: 1
Views: 1826
Reputation: 94739
I differentiate code for the mac using a test for the presence of the --version
option:
if ! date --version >/dev/null 2>&1; then # Mac
micro=$(perl -e 'use Time::HiRes qw( gettimeofday ); my ($a, $b) = gettimeofday; print $b;')
else
micro=$(($(date +%N) / 1000))
fi
The best accuracy for gettimeofday
is microseconds, though.
Upvotes: 2
Reputation: 46856
The OSX date
command doesn't do nanonseconds, but in OSX you can still get this from the system.
For example, in C, this should be the system uptime:
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
#include <mach/mach_time.h>
int main(void)
{
uint64_t t = mach_absolute_time();
// Get ratio between mach_absolute_time units and nanoseconds.
mach_timebase_info_data_t data;
mach_timebase_info(&data);
// Convert to nanoseconds.
t *= data.numer;
t /= data.denom;
printf("%" PRIu64 "\n", t);
return 0;
}
Save this to something like uptimens.c
, then run make uptimens
from your shell.
mac:~ ghoti$ ./uptimens
366181198555774
mac:~ ghoti$
Upvotes: 2
Reputation: 1
$ date +%T.%N 11:05:07.894987100
This gives you the current time with nanosecond accuracy.
Upvotes: -4