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

有时在执行完一段windows的批处理后,想知道这个过程花费了多少时间,若是是windows下的c代码能够在过程先后分别调用GetTickCount(),而后相减便可获得花费的时间。linux

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

在批处理中求值

下面的代码将打印出20windows

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

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

取得exe的返回值

用%errorlevel%能够取得执行一个exe以后其返回值。函数

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

 

GetTickCount程序

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

#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,并将其放到某个系统路径下。code

应用

@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%

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

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

linux下的bash实现计时

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

#!/bin/bash
start=$(date "+%s")

#do something
sleep 2

now=$(date "+%s")
time=$((now-start))
echo "time used:$time seconds"

 

~~~~Eureka~~~~

相关文章
相关标签/搜索