Written by razrlele
23:16 December 22, 2015
思路
运行一个程序,然后fork
出一个子进程来使用execl
运行目标程序,然后使用wait4
获取子进程所消耗的资源。
目标程序
1 2 3 4 5 6 7 8 |
#include <stdio.h> int main(){ long long i = 100000000; while(i--) ; return 0; } |
zsh
自带的资源监视结果
测试程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <cstdio> #include <unistd.h> #include <sys/resource.h> #include <sys/wait.h> int main(){ pid_t executive = fork(); if( executive < 0 ){ printf("fork failed\n"); return 0; } else if( executive == 0 ){ //child process execl("./hello", "hello", NULL); } else{ struct rusage rused; int status = 0; if( wait4( executive, &status, 0, &rused ) < 0 ){ printf("wait4 failed\n"); return 0; } if( WIFEXITED(status) ){ int time_usage = (rused.ru_utime.tv_sec * 1000 + rused.ru_utime.tv_usec / 1000); time_usage += ( rused.ru_stime.tv_sec * 1000 + rused.ru_stime.tv_usec / 1000 ); int memory_usage = rused.ru_minflt * ( getpagesize() / 1024 ); printf("Time used: %d MS Memory used: %d KB \n", time_usage, memory_usage); } } return 0; } |
输出结果
与实际结果基本相符~
原来这么简单。。。。囧rz