How to measure your CPU time: clock_gettime!

I loved reading How to measure your CPU time: clock_gettime! by Julia Evans.

In Perl, we can access clock_gettime throught the Time::HiRes module.

#!/usr/bin/env perl

# http://jvns.ca/blog/2016/02/20/measuring-cpu-time-with-clock-gettime/

use v5.22;
use warnings;
use Time::HiRes qw(clock_gettime CLOCK_PROCESS_CPUTIME_ID);

my $start_time = clock_gettime(CLOCK_PROCESS_CPUTIME_ID);
do_maybe_expensive_thing();
my $end_time = clock_gettime(CLOCK_PROCESS_CPUTIME_ID);
say "elapsed CPU time: ", $end_time - $start_time;

sub do_maybe_expensive_thing {
    my $j = 1;
    for my $i (1..int rand 100_000_000) {
        $j *= $i;
    }
}

If we change do_maybe_expensive_thing to just a sleep, we’ll see that it takes up time without using CPU time.

Fun!

Advertisements
How to measure your CPU time: clock_gettime!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s