有時(shí)需要計(jì)算程序運(yùn)行時(shí)間,這有許多方法,比如可以在調(diào)用函數(shù)前后記錄時(shí)間,相減就可以得到運(yùn)行時(shí)間。這需要在程序加入記錄代碼。也有方法不需要添加代碼也能統(tǒng)計(jì)。下面的程序是一個(gè)簡(jiǎn)單的計(jì)算運(yùn)行時(shí)間的工具,當(dāng)然和linux下的time無(wú)法相比。
/* 文件名:running.c
* 計(jì)算程序運(yùn)行時(shí)間
* author: lemene
* time: 2008-01-20
*/

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

extern char *optarg;
void usage()
{
printf("這是一個(gè)簡(jiǎn)易的計(jì)算程序運(yùn)行時(shí)間的工具\(yùn)n");
printf("usage: CodeCounter [-hEps] [string|n]\n");
printf("-h 顯示幫助信息\n");
printf("-E string 需要統(tǒng)計(jì)程序的路徑\n");
printf("-p string 程序運(yùn)行的參數(shù)\n");
printf("-s 是否顯示程序運(yùn)行窗口\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ù)錯(cuò)誤\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
測(cè)試:running -E CodeCounter.py -p "-d d:\dev-cpp -l -1"
輸出:running time: 12328ms
(注:CodeCounter.py 程序見(jiàn)《
Python寫(xiě)的簡(jiǎn)易代碼統(tǒng)計(jì)工具(2)》 )