The question is related to PDL: Looking for efficient way to extract sub-images, by finding bounding boxes of "objects". But I don't think it has anything to do with PDL, images, etc. The $str is just a very long string. Using $1 instead of $& doesn't help.

Perl is 5.20.2 Win32 Strawberry, or 5.24 Win64.

use strict; use warnings; use 5.020; use threads; use PDL; use PDL::IO::Image; use PDL::Image2D; use Encode qw/ decode /; PDL::no_clone_skip_warning; say "No thread\n---------"; say 'Count: ', scalar @{ test( 'test.png' )}; say "\nThread\n---------"; say 'Count: ', scalar @{ threads-> create( \&test, 'test.png' )-> join + }; sub test { my $fn = shift; my $img = PDL::IO::Image-> new_from_file( $fn ); my $pdl = $img-> pixels_to_pdl-> short; my $s = cc8compt( $pdl == 0 ); my $str = decode 'UTF16LE', ${ $s-> get_dataref }; my ( $w, $h ) = $s-> dims; my @b = map { [ [ $w, 0 ], [ $h, 0 ] ] } 0 .. $s-> max; my $t = time; for my $y ( 0 .. $h - 1 ) { my $s = substr( $str, $y * $w, $w ); while( $s =~ m[[^\0]+]g ) { my $c = ord( $& ); $b[ $c ][ 0 ][ 0 ] = $-[0] if $-[0] < $b[ $c ][ 0 +][ 0 ]; $b[ $c ][ 0 ][ 1 ] = $+[0] - 1 if $+[0] - 1 > $b[ $c ][ 0 +][ 1 ]; $b[ $c ][ 1 ][ 0 ] = $y if $y < $b[ $c ][ 1 +][ 0 ]; $b[ $c ][ 1 ][ 1 ] = $y if $y > $b[ $c ][ 1 +][ 1 ]; } } say 'Time: ', time - $t; shift @b; return \@b; }

The output:

No thread --------- Time: 2 Count: 145 Thread --------- Time: 52 Count: 145

In reply to Why this code is so slow if run in thread? by vr

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.