#include <stdio.h>
#include <stdlib.h>
#include <sys/times.h>
#include <unistd.h>
static void do_cmd( char * );
static void pr_times( clock_t, struct tms *, struct tms *);
int main( int argc, char *argv[] )
{
int i;
setbuf( stdout, NULL );
for( i = 1; i < argc; i++ )
do_cmd( argv[i] );
exit( 0 );
}
static void do_cmd( char *cmd )
{
struct tms tmsstart, tmsend;
clock_t start, end;
int status;
printf( "\ncommand: %s\n", cmd );
if( (start = times( &tmsstart )) < 0 )
printf( "times error\n" );
if( (status = system( cmd )) < 0 )
printf( "system error\n" );
if(( end = times( &tmsend ) ) < 0 )
printf( "times error\n" );
pr_times( end - start, &tmsstart, &tmsend );
}
static void pr_times( clock_t real, struct tms *tmsstart, struct tms *tmsend )
{
static long clktck = 0;
if( clktck == 0 )
if(( clktck = sysconf(_SC_CLK_TCK ) ) < 0 )
printf( "sysconf error\n" );
printf( " real: %7.2f\n", real / ( double )clktck );
printf( " user: %-7.2f\n",
(double)(tmsend->tms_utime - tmsstart->tms_utime) / clktck );
printf( " sys: %7.3f\n",
(double)(tmsend->tms_stime - tmsstart->tms_stime ) / clktck );
}
运行结果如下:
wangkai@ubuntu:~/Test$ ./a.out "sleep 5" "date"
command: sleep 5
real: 5.00
user: 0.00
sys: 0.000
command: date
2012年 05月 26日 星期六 06:07:43 PDT
real: 0.01
user: 0.00
sys: 0.000
wangkai@ubuntu:~/Test$