How to get / print nanotime?..

I'm missing the %N formatting (nanotime) in FreeBSD's date. And after searching the forums and net for a while, I still can't figure out how to get nanotime in FreeBSD.

I got a workaround with php's microtime() for now, but that's far from ideal.
 
Yes, I came across that man page. But that page is talking about include <sys/time.h>, and that's for when you're programming, right? (.h is a header file or something for C?) In other words, I have no idea how to use that in my simple shell script. I can't find any files called bintime, microtime, nanotime on my installation (nor with the get- prefix).
 
date(1) uses time(3), i.e. clock_gettime(CLOCK_SECOND, ...), and returns time only in seconds. But if you call clock_gettime(CLOCK_REALTIME, ...) you can get nanoseconds, too.

Knowing that you can easily write a wrapper against clock_gettime(2) using a FFI in the language of choice. Here is an example for Lua
Code:
$ ./time.lua
CLOCK_REALTIME = 1294965605.435817435
CLOCK_SECOND = 1294965605.000000000
$ date -r 1294965605
Fri Jan 14 00:40:05 UTC 2011
Code:
require 'alien'

local timespec = alien.defstruct {
   { 'sec',  'long' },
   { 'nsec', 'long' },
}

local CLOCK_REALTIME = 0
local CLOCK_SECOND = 13
local def = alien.default
def.clock_gettime:types('int', 'int', 'pointer')

function clock_gettime(clock)
   local tp = timespec:new()
   def.clock_gettime(clock, tp())
   return tp.sec, tp.nsec
end

-- here starts the program
sec, nsec = clock_gettime(CLOCK_REALTIME)
print('CLOCK_REALTIME = ' .. sec .. '.' .. string.format('%09d', nsec))

sec, nsec = clock_gettime(CLOCK_SECOND)
print('CLOCK_SECOND = ' .. sec .. '.' .. string.format('%09d', nsec))

Note, executing an external program such as date(1) will eat most of the precision for extra syscalls.
 
Tnx dandelion, but I'm not getting any of that, lol :)

I used a more pragmatic approach. Got the GNU core utils, compiled it, and copied the compiled date to /bin/date.gnu

Maybe not the neatest solution, but it works ;)
 
Back
Top