$shibayu36->blog;

クラスター株式会社のソフトウェアエンジニアです。エンジニアリングや読書などについて書いています。

perlの変数のデータ量を測定する

perlの変数のデータ量を調べたいということがあって、何を使ったらいいか調べたんだけど、Devel::Sizeというのが便利そうだった。

こんなかんじで使える。

use Devel::Size qw(size total_size);
 
my $size = size([1, 2, 3, 4, 5]);
warn $size;

my $total_size = total_size({
    a => [1, 2, 3],
    b => {
        c => [1, 3, 5],
    },
});
warn $total_size;


sizeというのは構造のために使われている容量を出してくれるやつ。

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.


ちゃんと容量を知りたかったらtotal_sizeというのを使わないといけない。

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.


ひとまずバイト単位で簡単に出してくれるので便利。ただやってみると意外とPerlメモリ使うなあという気持ちになる。