码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2015-10-20 19:12:59      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

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

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

在批处理中求值

下面的代码将打印出20

1 @echo off
2 set cho=23
3 set /a res=%cho% - 3
4 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 2

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

 

~~~~Eureka~~~~

 

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

标签:

原文地址:http://www.cnblogs.com/xiangism/p/4895509.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!