Super User is a question and answer site for computer enthusiasts and power users. 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

I want to generate a textual timestamp in the unix shell with microsecond accuracy, without using the %N date option (I am using busybox, a smaller unix toolset that does not have this option), to prefix to output I am generating. The timestamp should have the format "<seconds since epoc>.<microseconds>".

awk -f ./myawkscript.awk < /param | sed 's/$/\[<TIMESTAMP WOULD GO HERE>].'

So the desired output would look like:

[1305638345.123456] awk script output

I can obtain the epoc easy enough using date +"%s", so my question is, is there a way of obtaining the microseconds from the shell?

share|improve this question
#include <stdio.h>
#include <sys/time.h>

int main() {
    struct timeval t;

    if (gettimeofday(&t, NULL) == 0)
        printf("%d.%06u\n", t.tv_sec, t.tv_usec);

    return 0;
}

Compile with cc -o timestamp timestamp.c

For completeness: clock_gettime() can return nanoseconds, but with an awk script you wouldn't reach that accuracy anyway.

share|improve this answer

Does busybox date accept the %N (nanoseconds) field?

time=$(date "+%s.%N")

To remove the "nano-ness"

time=$(date "+%s.%N" | cut -c 1-17)

or

time=$(date "+%s.%N"); time=${time%???}
share|improve this answer
2  
To quote the question, "without using the %N date option (I am using busybox, a smaller unix toolset that does not have this option)" – grawity May 25 '11 at 6:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .