In a shell script (sh), how do I store the time in milliseconds (or
microseconds, don't care) to a variable?
Thanks, - Dave
Where shall the milli-(micro-)seconds come from? (Actual time?)
Depending on what shell the 'sh' actually is, in a modern ksh93 you can do
ms=${SECONDS#*.}
(For plain sh Bourne shells you'd have to rely on external programs.)
Janis
>
> Thanks, - Dave
I meant milliseconds/microseconds from the actual time, yes. I wrote
this, but sadly it always produces zero:
#!/bin/sh
ms=${SECONDS#*.}
echo $ms
I'm on a Mac OS 10.5.6. Here is what I see in response to uname -a:
Darwin ocho.local 9.6.0 Darwin Kernel Version 9.6.0: Mon Nov 24
17:37:00 PST 2008; root:xnu-1228.9.59~1/RELEASE_I386 i38
Well, as Janis wrote, for plain Bourne shells this won't work. It's
likely that /bin/sh is a Bourne shell (or a link to bash).
> I'm on a Mac OS 10.5.6. Here is what I see in response to uname -a:
uname won't really help. You need to know what shell /bin/sh is. But
on OS X it's likely bash.
I don't think that ksh code will give you what you want anyway; if my
reading of the man page is right, it gives you the number of seconds
since shell invocation, not absolute milliseconds. (You may need to
install a newer version of ksh on your OS X box.) bash has a similar
variable (though AFAICT it doesn't do any unit smaller than seconds).
What exactly are you trying to accomplish? What is it you're measuring
that you think you need milliseconds?
--keith
--
kkeller...@wombat.san-francisco.ca.us
(try just my userid to email me)
AOLSFAQ=http://www.therockgarden.ca/aolsfaq.txt
see X- headers for PGP signature information
Not in the shell, but with per:
perl -MTime::HiRes -e 'print int(1000 * Time::HiRes::gettimeofday),"\n"'
The overhead of invoking perl will certainly add a few milleseconds...
--
Glenn Jackman
Write a wise saying and your name will live forever. -- Anonymous
About 22-23 milliseconds for the overhead of each iteration below:
#! /bin/bash
i=0
while [ $i -le 60 ]
do
ms=$( perl -MTime::HiRes -e 'print int(1000 *
Time::HiRes::gettimeofday),"\n"' )
sec=$( date '+%S' )
printf '%2d %d\n' "$sec" "$ms"
sleep 1
i=$(( $i + 1 ))
done
I'm sure there are better ways to do this so feel free.
> In a shell script (sh), how do I store the time in milliseconds (or
> microseconds, don't care) to a variable?
nano seconds since 1970-01-01 00:00:00 UTC:
$ date --version|head -n1
date (GNU coreutils) 7.6
$ NS=`date +%s%N`
$ echo $NS
1256090733975302128
Yes, that's correct.
This will give current nanoseconds, on new-enough ksh93:
ns=$(printf "%(%N)T")
John
--
John DuBois spc...@armory.com KC6QKZ/AE http://www.armory.com/~spcecdt/