老板叫我帮他测一个命令在windows下消耗的时间,由于没有装windows那个啥工具包,没有timeit那个命令,因而想本身写一个,原理很简单:python
REM timeit.bat echo %TIME% call %* echo %TIME%
而后两个时间减一下就能够了,可是老是本身去减始终不方便,最好能直接算好打印出来。git
由于涉及到时间格式的解析,时间的运算,在batch下比较困难,天然就想到了python或者perl脚本,这里首先想到的是python的-c参数:github
REM timeit.bat set t1 = %TIME% call %* set t2 = %TIME% python -c "some python code to compute the time elapsed"
可是,因为计算的代码会比较复杂,直接放在一行上很是难写,也很是难读,最好能分多行写python代码,咱们知道bash中有个heredoc,结合python的 “-” 参数:windows
# test.sh echo this is a bash script python - <<EOF import math print "this is python code" print math.pi EOF
无奈,batch并不支持heredoc,因此在要在batch中实现这个,用到一个很是magic的方法:原理就是个人脚本既是合法的batch,也是合法的python,而后在batch运行的最后用python调用自身:bash
1># : ^ ''' set t1 = %TIME% call %* set t2 = %TIME% python %~f0" exit /b rem ^ ''' import os import datetime # python code to compute the time elapsed print "Time Elapsed: xxx"
具体解释能够看这个问题:http://stackoverflow.com/questions/17467441/how-to-embed-python-code-in-batch-script工具
注意第一行奇怪的语法只是为了把第二行合法的移到第一行,从而避免三个单引号这个非法命令调用出如今batch中。this
完整的timeit的实如今这里:https://github.com/lzprgmr/privaterepo/blob/master/tools/Batch/timeit.batspa
最后,固然有人会说为何不直接写一个py而后在batch中调用 - 这固然能够,但我想尽可能保持一个功能在一个脚本中,这样看起来整洁,给别人用拷来拷去也不容易出错。code