awk

Awk Profiler - pgawk

pgawk程序用于创建你的awk程序的执行配置文件。使用pgawk您可以查看每个AWK语句(以及用户自定义函数)执行多少时间。

首先,创建一个awk程序示例,我们将通过pgawk运行查看,配置如何输出的。

$ cat profiler.awk
BEGIN {
    FS=",";
    print "Report Generated On:" strftime("%a %b %d %H:%M:%S %Z %Y",systime());
}
{
if ($5 <= 5 )
    print "Buy More: Order", $2, "immediately!"
else
    print "Sell More: Give discount on", $2, "immediately!"
}
END {
    print "----"
}

接下来,使用pgawk执行样本awk程序(取代awk)。

$ awk -f profiler.awk items.txt
Report Generated On:Sun Aug 30 13:22:00 CST 2015
Sell More: Give discount on HD Camcorder immediately!
Buy More: Order Refrigerator immediately!
Sell More: Give discount on MP3 Player immediately!
Sell More: Give discount on Tennis Racket immediately!
Buy More: Order Laser Printer immediately!
----

默认情况下pgawk创建了一个名为myprofiler.out (或awkprof.out )文件。使用--profiler选项,如下所示,您可以指定自己的分析器输出文件名。

$ pgawk --profile=myprofiler.out -f profiler.awk  items.txt
Report Generated On:Sun Aug 30 13:25:04 CST 2015
Sell More: Give discount on HD Camcorder immediately!
Buy More: Order Refrigerator immediately!
Sell More: Give discount on MP3 Player immediately!
Sell More: Give discount on Tennis Racket immediately!
Buy More: Order Laser Printer immediately!
----

查看默认awkprof.out理解各个AWK语句的执行计数。

$ cat myprofiler.out
    # gawk profile, created Sun Aug 30 13:25:04 2015

    # BEGIN block(s)

    BEGIN {
     1      FS = ","
     1      print ("Report Generated On:" (strftime("%a %b %d %H:%M:%S %Z %Y", systime())))
    }

    # Rule(s)

     5  {
     5      if ($5 <= 5) { # 2
     2          print "Buy More: Order", $2, "immediately!"
     3      } else {
     3          print "Sell More: Give discount on", $2, "immediately!"
        }
    }

    # END block(s)

    END {
     1      print "----"
    }

在阅读awkprof.out ,请记住以下几点:

* 左边的列包含一个编号。这表明了,特定awk命令已经执行多少次。例如,在打印语句在BEGIN里只执行一次(废话!)。if 循环执行5次。

* 任何条件的检查,一个在左侧,另一个在右边的括号后。左侧表示pattern多少次检验。右侧表示它多少次成功。在上面的例子中,条件被执行了5次,但是它成功的只有2次,if语句旁边所指示的 ( # 2 )。