Linux中是否有shell命令以毫秒为单位获取时间?
当前回答
下面是一个在Linux上以毫秒为单位获取时间的便携式hack:
#!/bin/sh
read up rest </proc/uptime; t1="${up%.*}${up#*.}"
sleep 3 # your command
read up rest </proc/uptime; t2="${up%.*}${up#*.}"
millisec=$(( 10*(t2-t1) ))
echo $millisec
输出结果为:
3010
这是一个非常廉价的操作,它与shell内部程序和procfs一起工作。
其他回答
我只是想在Alper的回答中补充一下我必须做的事情:
在Mac上,你需要brew install coreutils,所以我们可以使用gdate。否则在Linux上,它只是日期。这个函数将帮助您执行命令,而无需创建临时文件或任何东西:
function timeit() {
start=`gdate +%s%N`
bash -c $1
end=`gdate +%s%N`
runtime=$(((end-start)/1000000000.0))
echo " seconds"
}
你可以将它与字符串一起使用:
timeit 'tsc --noEmit'
date +%s%N返回秒数+当前纳秒。
因此,echo $(($(date +%s%N)/1000000))就是您所需要的。
例子:
$ echo $(($(date +%s%N)/1000000))
1535546718115
Date +%s返回自epoch以来的秒数,如果有用的话。
当你从4.1版本开始使用GNU AWK时,你可以加载时间库并执行以下操作:
$ awk '@load "time"; BEGIN{printf "%.6f", gettimeofday()}'
这将以秒为单位打印自1970-01-01T00:00:00以来的当前时间,精度为亚秒。
the_time = gettimeofday() Return the time in seconds that has elapsed since 1970-01-01 UTC as a floating-point value. If the time is unavailable on this platform, return -1 and set ERRNO. The returned time should have sub-second precision, but the actual precision may vary based on the platform. If the standard C gettimeofday() system call is available on this platform, then it simply returns the value. Otherwise, if on MS-Windows, it tries to use GetSystemTimeAsFileTime(). source: GNU awk manual
在Linux系统上,标准C函数getimeofday()以微秒精度返回时间。
Perl可以用于此目的,甚至在AIX这样的特殊平台上也是如此。例子:
#!/usr/bin/perl -w
use strict;
use Time::HiRes qw(gettimeofday);
my ($t_sec, $usec) = gettimeofday ();
my $msec= int ($usec/1000);
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime ($t_sec);
printf "%04d-%02d-%02d %02d:%02d:%02d %03d\n",
1900+$year, 1+$mon, $mday, $hour, $min, $sec, $msec;
日期+“% T。%N"返回当前时间,单位为纳秒。 06:46:41.431857000 日期+“% T。%6N”返回当前时间,其中纳秒四舍五入到前6位数字,即微秒。 06:47:07.183172 日期+“% T。%3N”返回当前时间,将纳秒四舍五入到前3位数字,即毫秒。 06:47:42.773
通常,date命令格式的每个字段都可以指定可选的字段宽度。