随笔 - 51, 文章 - 1, 评论 - 41, 引用 - 0
数据加载中……

简易统计程序运行时间的程序

         有时需要计算程序运行时间,这有许多方法,比如可以在调用函数前后记录时间,相减就可以得到运行时间。这需要在程序加入记录代码。也有方法不需要添加代码也能统计。下面的程序是一个简单的计算运行时间的工具,当然和linux下的time无法相比。
/* 文件名:running.c
 
* 计算程序运行时间 
 
* author: lemene
 
* time2008-01-20
 
*/

#include 
<windows.h>
#include 
<stdio.h>
#include 
<getopt.h>

extern char 
*optarg; 
void usage()
{
    printf(
"这是一个简易的计算程序运行时间的工具\n");
    printf(
"usage: CodeCounter [-hEps] [string|n]\n");
    printf(
"-h          显示帮助信息\n");
    printf(
"-E string   需要统计程序的路径\n");
    printf(
"-p string   程序运行的参数\n");
    printf(
"-s          是否显示程序运行窗口\n");

}

void running(
const char* f, const char* p, int show)
{
    SHELLEXECUTEINFO   ExeInfo;   
    ZeroMemory(
&ExeInfo,sizeof(SHELLEXECUTEINFO));   
    ExeInfo.cbSize   
=   sizeof(SHELLEXECUTEINFO);   
    ExeInfo.lpFile   
=   f;   
    ExeInfo.fMask   
=   SEE_MASK_NOCLOSEPROCESS   ;   
    ExeInfo.nShow   
=   show ? SW_SHOWNORMAL : SW_HIDE;
    ExeInfo.lpParameters 
= p;
    ShellExecuteEx(
&ExeInfo);   
    WaitForSingleObject(ExeInfo.hProcess,INFINITE);       
}

void err_msg()
{
    printf(
"参数错误\n");
    printf(
"running -h 查看帮助信息\n");
}

int main(int argc,char **argv)
{
    char file[MAX_PATH] 
= {0};
    char param[
512];
    
int opt;
    DWORD start;
    
int show = 0;
    
while((opt=getopt(argc,argv,"hE:p:s"))!=-1)
    {
        switch (opt)
        {
        
case 'h':
            usage();
            return 
0;
        
case 'p':
            strcpy(param, optarg);
            break;
        
case 'E':
            strcpy(file, optarg);
            break;
        
case 's':
            show = 1;
            break;
        default:
            err_msg();
            return 
0;
        }
    }
    
if (file[0== 0)
    {
        err_msg();
        return 
0;
    }
    start 
= GetTickCount();
    running(file, param, show);
    printf(
"running time: %dms\n", GetTickCount()-start);
    
    return 
1;
}
编译:gcc -o running.exe running.c -O
测试:running -E CodeCounter.py -p "-d d:\dev-cpp -l -1"
输出:running time: 12328ms
(注:CodeCounter.py 程序见《Python写的简易代码统计工具(2)》


posted on 2008-03-17 16:22 lemene 阅读(2175) 评论(3)  编辑 收藏 引用

评论

# re: 简易统计程序运行时间的程序  回复  更多评论   

谢谢!
2009-08-13 16:23 | 千张

# re: 简易统计程序运行时间的程序  回复  更多评论   

不好意思 我是菜鸟 请帮忙解释如何使用呀
2009-12-12 11:27 | 000

# re: 简易统计程序运行时间的程序[未登录]  回复  更多评论   

以这个段代码为例:
running -E CodeCounter.py -p "-d d:\dev-cpp -l -1"
它测试程序CodeCounter.py -d d:\dev-cpp -l -1的运行时间。
CodeCounter.py 是被测程序,"-d d:\dev-cpp -l -1"是被侧程序的参数。
2009-12-14 21:54 | lemene

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理