有時需要計算程序運行時間,這有許多方法,比如可以在調(diào)用函數(shù)前后記錄時間,相減就可以得到運行時間。這需要在程序加入記錄代碼。也有方法不需要添加代碼也能統(tǒng)計。下面的程序是一個簡單的計算運行時間的工具,當然和linux下的time無法相比。
/* 文件名:running.c
* 計算程序運行時間
* author: lemene
* time: 2008-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 需要統(tǒng)計程序的路徑\n");
printf("-p string 程序運行的參數(shù)\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("參數(shù)錯誤\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寫的簡易代碼統(tǒng)計工具(2)》 )