2023 twenty-four merry days of Perl Feed

Introduction to App::Timer

App::Timer - 2023-12-10

Background

So what is it that I am going to talk about today?

As you all know I have handful of distributions available on MetaCPAN. Although I am not actively managing any of them but I do look after them as and when needed.

If you look at the list of my distributions, you would notice that some of them are just plain application i.e. something that can be executed at the command prompt. One of them, e.g. App::calendr. Every time, I run an application, I always wanted to know how long it took to complete the execution.

For many years, I used to add the following snippets at the end of my command line application script.

END {
    my $time = time - $^T;
    my $mm = $time / 60;
    my $ss = $time % 60;
    my $hh = $mm / 60;

    printf("The program ran for %02d:%02d:%02d.\n", $hh, $mm%60, $ss);
}

Proposals

Can I do something that works for every command line applications?

Well, I gave a deep thought one weekend and ended up quick and dirty solution, App::Timer.

To be honest, there is no Rocket Science behind it. However it is very handy and help me with all my command line applications.

There are 2 ways you can have the timer added to your application.

Import the module

You can simply add one line use App::Timer at the top and you are done.

Command line switch

Not always you want to touch the application source code, so you can use the command line switch instead as below:

    $ perl -MApp::Timer your-application.pl

Perl being the Perl, you can get away not doing any of the above and simply do this:

    $ time perl your-application.pl

If you use App::Timer, you can expect the command line output to look something like this:

    $ perl -MApp::Timer -E 'sleep 1'
    The program ran for 00:00:01.

That's it for today, have an enjoyable holiday break.

Gravatar Image This article contributed by: Mohammad Anwar <mohammad.anwar@yahoo.com>