Windows 命令执行时间统计方式

Windows 命令执行时间统计方式

前言

​ 日常开发过程中经常会遇见需要统计命令执行时间的需求,所以本片文章主要记录一下本人经常使用的几种方式。

常用方式
Measure-Command
介绍

在内部执行脚本并计算操作的执行时间。

使用方式
Measure-Command{你的命令}

例如:Measure-Command{echo hello}

Measure-Command{echo hello}
----------------------------------------------
Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 11
Ticks             : 117058
TotalDays         : 1.35483796296296E-07
TotalHours        : 3.25161111111111E-06
TotalMinutes      : 0.000195096666666667
TotalSeconds      : 0.0117058
TotalMilliseconds : 11.7058
优缺点

优点:Windows PowerShell 自带的命令行工具,无需自己编写多余命令

缺点:CMD 不能够使用此命令,不能够定制化时间格式。

BAT脚本
介绍

通过自己编写另外一个bat脚本来计算执行其他命令的执行时间。

脚本

TimeScope.bat

@echo off
@setlocal

set start=%time%

:: 开始执行命令
cmd /c %*
set end=%time%
set options="tokens=1-4 delims=:.,"
for /f %options% %%a in ("%start%") do set start_h=%%a&set /a start_m=100%%b %% 100&set /a start_s=100%%c %% 100&set /a start_ms=100%%d %% 100
for /f %options% %%a in ("%end%") do set end_h=%%a&set /a end_m=100%%b %% 100&set /a end_s=100%%c %% 100&set /a end_ms=100%%d %% 100
set /a hours=%end_h%-%start_h%
set /a mins=%end_m%-%start_m%
set /a secs=%end_s%-%start_s%
set /a ms=%end_ms%-%start_ms%
if %ms% lss 0 set /a secs = %secs% - 1 & set /a ms = 100%ms%
if %secs% lss 0 set /a mins = %mins% - 1 & set /a secs = 60%secs%
if %mins% lss 0 set /a hours = %hours% - 1 & set /a mins = 60%mins%
if %hours% lss 0 set /a hours = 24%hours%
if 1%ms% lss 100 set ms=0%ms%
:: 计算时间并输出
set /a totalsecs = %hours%*3600 + %mins%*60 + %secs%
echo execution time %hours%:%mins%:%secs%.%ms% (%totalsecs%.%ms%s total)

%*:表示批处理文件的所有参数,此处可以理解为待统计执行时间的命令。

使用方式
TimeScope.bat echo hello
-----------------------
hello
execution time 0:0:0.01 (0.01s total)
优缺点

优点:可以在任意命令行工具中使用,可定制自己的时间格式,自由度高。

缺点:需要拷贝当前脚本到执行命令的机器/电脑上。

常用命令拓展
  • %cd%:当前执行命令的目录,例如 cd %cd%,进入当前执行命令的目录。
  • taskkill /f /im 进程:杀掉进程,例如 taskkill /f /im nginx.exe ,杀掉nginx进程。
  • 命令 /?:命令使用文档,例如 cd /?,查看cd的使用文档
  • findstr:查找某个内容,同Linux 中的grep,例如 dir ./ | findstr test.txt,查找当前文件夹下包含test.txt的文件或者文件夹。
  • %[1-9]:表示传递参数,例如 test.bat hello ,在脚本中可是使用%1表示获取第一个参数,此处即获取到了hello,%0表示命令本身。
  • cd \:表示进入命令执行的根目录,例如 C:\Users\Administrator>cd \ ,则会进入到C:\>
常用软件

process-explorer:可以查看进程使用了哪个dll等信息。

总结

以上即是我日常工作中使用到的方式,如大家有更好的方法请联系或评论,谢谢大家的观看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值