实现windows批处理下的计时功能

时间:2023-03-09 03:44:31
实现windows批处理下的计时功能

有时在执行完一段windows的批处理后,想知道这个过程花费了多少时间,如果是windows下的c代码可以在过程前后分别调用GetTickCount(),然后相减即可得到花费的时间。

但是如果在批处理中就没有这样现成的函数,并且在本人在网上找了好久都没找到。最后在搞定了批处理变量计算,从exe中取得返回值等技术点后,最终实现了这个功能。

在批处理中求值

下面的代码将打印出20

 @echo off
set cho=23
set /a res=%cho% - 3
echo %res%

注意,第一个set后面=前后一定不能加空格,第二个set后一定得有/a

取得exe的返回值

用%errorlevel%可以取得执行一个exe之后其返回值。

@echo off
start /wait Program.exe
set r=%errorlevel%
echo %r%

GetTickCount程序

写一个简单的c程序,调用GetTickCount()将其值返回

#include <windows.h>
#include <stdio.h> int main(int argc, char** argv)
{
int t = GetTickCount();
printf("%d\n", t);
return t;
}

随便用一个c的编译器,将上面的c源码编译成exe程序,取名为GetTickCount.exe,并将其放到某个系统路径下。

应用

@echo off
start /wait GetTickCount.exe
set t1=%errorlevel% sleep 3
::TODO Something start /wait GetTickCount.exe
set t2=%errorlevel% set /a t=%t2%-%t1%
echo %t%

最后将打印出以毫秒为单位的时间花费。

GetTickCount的下载路径http://files.cnblogs.com/files/xiangism/GetTickCount.rar

linux下的bash实现计时

顺便贴出如何在linux下的shell中实现计时

#!/bin/bash
start=$(date "+%s") #do something
sleep now=$(date "+%s")
time=$((now-start))
echo "time used:$time seconds"

~~~~Eureka~~~~