shell 执行某个命令的时间


比如,我想编译个源码,执行 make 之后
突然想记时看看 make 命令要运行多久才能结束,不用到 cpu 时间片级别的,用户级别就成

别说 date 一下,等执行完了再 date 相减,
有木有再优雅点的?

Linux shell

skidy 10 years, 10 months ago

如楼上所说的,用time命令可以看到程序运行的时间:

   
  [ajaxhe@localhost ~]$ time date
  
Sat Dec 8 22:39:06 CST 2012

real 0m0.040s
user 0m0.003s
sys 0m0.009s

time命令结果有三行组成:real、user和sys。real值表示从程序开始到程序执行结束时所消耗的时间,包括CPU的用时。CPU用时被划分为user和sys两块。user值表示程序本身,以及它所调用的库中的子例程使用的时间。sys是由程序直接或间接调用的系统调用执行的时间。

当然了,你也可以通过times()以及system()自己实现,如下:

   
  #include <sys/times.h>
  
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

static void pr_times(clock_t, struct tms *, struct tms *);
static void do_cmd(char *);

int
main(int argc, char *argv[])
{

int i;

setbuf(stdout, NULL);
for (i = 1; i < argc; i++)
do_cmd(argv[i]); /* once for each command-line arg */
exit(0);
}

static void
do_cmd(char *cmd) /* execute and time the "cmd" */
{
struct tms tmsstart, tmsend;
clock_t start, end;
int status;

printf("\ncommand: %s\n", cmd);

if ((start = times(&tmsstart)) == -1) /* starting values */
{
fprintf(stderr, "times error");
exit(-1);
}

if ((status = system(cmd)) < 0) /* execute command */
{
fprintf(stderr, "system() error");
exit(-1);
}

if ((end = times(&tmsend)) == -1) /* ending values */
{
fprintf(stderr, "times error");
exit(-1);
}

pr_times(end-start, &tmsstart, &tmsend);

exit(status);
}
static void
pr_times(clock_t real, struct tms *tmsstart, struct tms *tmsend)
{
static long clktck = 0;

if (clktck == 0) /* fetch clock ticks per second first time */
if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
{
fprintf(stderr, "sysconf error");
exit(-1);
}
printf(" real: %7.2f\n", real / (double) clktck);
printf(" user: %7.2f\n",
(tmsend->tms_utime - tmsstart->tms_utime) / (double) clktck);
printf(" sys: %7.2f\n",
(tmsend->tms_stime - tmsstart->tms_stime) / (double) clktck);
printf(" child user: %7.2f\n",
(tmsend->tms_cutime - tmsstart->tms_cutime) / (double) clktck);
printf(" child sys: %7.2f\n",
(tmsend->tms_cstime - tmsstart->tms_cstime) / (double) clktck);
}
   
  $ ./a.out "sleep 5" "date"
  

command: sleep 5
real: 5.02
user: 0.00
sys: 0.00
child user: 0.01
child sys: 0.00
normal termination, exit status = 0

command: date
Mon Mar 22 00:43:58 EST 2004
real: 0.01
user: 0.00
sys: 0.00
child user: 0.01
child sys: 0.00
normal termination, exit status = 0

以上代码来自《UNIX环境高级编程》第8.16小节。

MOU御用黑锅 answered 10 years, 10 months ago

Your Answer