#include <sys/times.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> //時間統計函數 static void get_times(clock_t real, struct tms *tmsstart, struct tms *tmsend) { static long clktck = 0; if (clktck == 0) //第一次獲得時間 if ((clktck = sysconf(_SC_CLK_TCK)) < 0) { perror("調用sysconf函數錯誤.\n"); } //以下為時間輸出 printf("時鐘時間: %7.2f\n", real / (double) clktck); printf("用戶CPU時間: %7.2f\n",(tmsend->tms_utime - tmsstart->tms_utime) / (double) clktck); printf("系統CPU時間: %7.2f\n",(tmsend->tms_stime - tmsstart->tms_stime) / (double) clktck); printf("子進程時鐘時間: %7.2f\n",(tmsend->tms_cutime - tmsstart->tms_cutime) / (double) clktck); printf("子進程系統CPU時間: %7.2f\n",(tmsend->tms_cstime - tmsstart->tms_cstime) / (double) clktck); } //執行并且對cmd命令計時 static void execute_cmd(char *cmd) { struct tms tmsstart, tmsend; //時間結構體; clock_t start, end; //分別存放起始和停止時刻的時鐘滴答數 int status; //執行狀態 printf("\n當前執行的命令是: %s\n", cmd); //輸出對應的命令 if ((start = times(&tmsstart)) == -1) //獲得start時間 { perror("調用times函數出錯.\n"); } if ((status = system(cmd)) < 0) //執行命令 { perror("調用system函數出錯\n"); } if ((end = times(&tmsend)) == -1) //獲得end時間 { perror("調用times函數出錯\n"); } get_times(end-start, &tmsstart, &tmsend); //計算運行時間 } //主函數 int main(int argc, char *argv[]) { int i; setbuf(stdout, NULL); //清空標準輸出(屏幕) if(argc != 2) //參數數目錯誤 { printf("請輸入正確的命令.\n"); exit(0); } else { execute_cmd(argv[1]); //執行命令 exit(0); } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。