使用Devel系列模块调试Perl脚本
一、Devel::Size 查看内存用量二、Devel::Timer 查看函数耗时
一、Devel::Size 查看内存用量
在开发过程需要查看变量所使用的内存大小,主要用于调试代码中对内存的使用量的情况。
Devel::Size - Perl extension for finding the memory usage of Perl variables
This module figures out the real size of Perl variables in bytes, as accurately as possible.
Call functions with a reference to the variable you want the size of. If the variable is a plain scalar it returns the size of this scalar. If the variable is a hash or an array, use a reference when calling.
它有两个函数可供导出:
size($ref)
The size function returns the amount of memory the variable returns. If the variable is a hash or an array, it only reports the amount used by the structure, not the contents.
size函数返回变量的内存总量。如果变量是一个散列或一个数组,它只报告其结构所使用的数量,而不是内容所占用的内存。
total_size($ref)
The total_size function will traverse the variable and look at the sizes of contents. Any references contained in the variable will also be followed, so this function can be used to get the total size of a multidimensional data structure. At the moment there is no way to get the size of an array or a hash and its elements without using this function.
total_size函数将遍历变量,并查看内容的大小。任何引用包含在变量也包含在其中,所以这个函数可以用来获取一个多维数据结构的总大小。除此之外目前没有办法得到数组或散列和它的元素的大小。
示例:
use Devel::Size qw(size total_size);
my @arr;
$arr[100]=1;
print total_size(\@arr);
my @foo = (1, 2, 3, 4, 5);
my $other_size = size(\@foo);
my $foo = {a => [1, 2, 3],
b => {a => [1, 3, 4]}
};
my $total_size = total_size($foo);
二、Devel::Timer 查看函数耗时
Devel::Timer - Track and report execution time for parts of code
对部分代码跟踪报告执行时间。找出执行最慢的例程非常有用。
Devel::Timer allows developers to accurately time how long a specific piece of code takes to execute. This can be helpful in locating the slowest parts of an existing application.
对象初始
use Devel::Timer;
my $t = Devel::Timer->new();
开始调用mark函数做标记
Second, markers are placed before and after pieces of code that need to be timed. For this example, we are profiling the methods get_user_score() and get_average_user_score().
$t->mark('first db query');
get_freeoa_user_score($user);
$t->mark('second db query');
get_average_user_score();
Finally, at the end of the code that you want to profile, and end marker is place, and a report is generated on stderr.
最后,可做一个结束标记,调用report函数将报告将输出的stderr。
$t->mark('END');
$t->report();
下面是一个将mysql中的数据导出处理后导入到postgresql中的输出示例:
Devel::Timer Report -- Total time: 2.9221 secs
Interval Time Percent
----------------------------------------------
04 -> 05 2.0461 70.02% all prepared and insert to pg -> set_topgsql()
01 -> 02 0.8749 29.94% all inited and prepare to get data fromysql -> get_fromysql()
00 -> 01 0.0011 0.04% INIT -> all inited and prepare to get data fromysql
02 -> 03 0.0000 0.00% get_fromysql() -> hand_sqlrs()
03 -> 04 0.0000 0.00% hand_sqlrs() -> all prepared and insert to pg
该文章最后由 阿炯 于 2017-05-14 18:41:08 更新,目前是第 2 版。