Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

2 Answers

#include <stdio.h>
#include <sys/time.h>
int main() {
    struct timeval t;
    struct timezone tz;

    if (gettimeofday(&t, &tz) == 0)
        printf("%d.%d\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
add comment

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
    
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
add comment

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.