是否有一种内置的方法来测量Windows命令行上命令的执行时间?


当前回答

The following script uses only "cmd.exe" and outputs the number of milliseconds from the time a pipeline is created to the time that the process preceding the script exits. i.e., Type your command, and pipe the to the script. Example: "timeout 3 | runtime.cmd" should yield something like "2990." If you need both the runtime output and the stdin output, redirect stdin before the pipe - ex: "dir /s 1>temp.txt | runtime.cmd" would dump the output of the "dir" command to "temp.txt" and would print the runtime to the console.

:: --- runtime.cmd ----
@echo off
setlocal enabledelayedexpansion

:: find target for recursive calls
if not "%1"=="" (
    shift /1
    goto :%1
    exit /b
)

:: set pipeline initialization time
set t1=%time%

:: wait for stdin
more > nul

:: set time at which stdin was ready
set t2=!time!

::parse t1
set t1=!t1::= !
set t1=!t1:.= !
set t1=!t1: 0= !

:: parse t2
set t2=!t2::= !
set t2=!t2:.= !
set t2=!t2: 0= !

:: calc difference
pushd %~dp0
for /f %%i in ('%0 calc !t1!') do for /f %%j in ('%0 calc !t2!') do (
    set /a t=%%j-%%i
    echo !t!
)
popd
exit /b
goto :eof

:calc
set /a t=(%1*(3600*1000))+(%2*(60*1000))+(%3*1000)+(%4)
echo !t!
goto :eof

endlocal

其他回答

还有TimeMem(2012年3月):

这是一个Windows实用程序,执行一个程序并显示它 执行时间、内存使用和IO统计信息。这与 Unix time实用程序的功能。

因为其他人建议安装像免费软件和PowerShell这样的东西,你也可以安装Cygwin,它可以让你访问许多基本的Unix命令,比如time:

abe@abe-PC:~$ time sleep 5

real    0m5.012s
user    0m0.000s
sys 0m0.000s

不知道Cygwin增加了多少开销。

PowerShell为此提供了一个cmdlet,称为Measure-Command。您必须确保在运行PowerShell的机器上是可用的。

PS> Measure-Command { echo hi }

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 1318
TotalDays         : 1.52546296296296E-09
TotalHours        : 3.66111111111111E-08
TotalMinutes      : 2.19666666666667E-06
TotalSeconds      : 0.0001318
TotalMilliseconds : 0.1318

Measure-Command捕获命令的输出。你可以使用Out-Default将输出重定向回控制台:

PS> Measure-Command { echo hi | Out-Default }
hi

Days              : 0
...

正如Makotoe所评论的那样,Measure-Command返回一个TimeSpan对象,因此测量的时间被打印为一堆字段。你可以使用ToString()将对象格式化为时间戳字符串:

PS> (Measure-Command { echo hi | Out-Default }).ToString()
hi
00:00:00.0001318

如果Measure-Command中的命令改变了控制台文本的颜色,使用[console]::ResetColor()将其重置为正常。

在Perl安装了可用的雇佣解决方案后,运行:

C:\BATCH>time.pl "echo Fine result"
0.01063
Fine result

STDERR出现在被测量的秒之前

#!/usr/bin/perl -w

use Time::HiRes qw();
my $T0 = [ Time::HiRes::gettimeofday ];

my $stdout = `@ARGV`;

my $time_elapsed = Time::HiRes::tv_interval( $T0 );

print $time_elapsed, "\n";
print $stdout;

powershell的另一种方法:

@echo off
for /f %%t in ('powershell "(get-date).tofiletime()"') do set mst=%%t

rem some commands

powershell ((get-date).tofiletime() - %mst%)

这将以毫秒为单位打印执行时间。