in reply to Why this code is so slow if run in thread?
Update:I just looked back at your code as opposed to my mock-up of it and realised this can't be the cause because you are not timing the return.
Why this code is so slow if run in thread?
Because you are returning a ref to an array of arrays, which in the unthreaded code means simply returning a scalar; but in the threaded code, means duplicating the entire contents of that AoAs into the calling threads memory and then returning a reference to the copy.
This can be demonstrated without PDL or Encode like this:
#! perl -slw use strict; use threads; use Time::HiRes qw[ time ]; sub test { my @b = map[[0,0],[0,0]], 0 .. 255; return \@b; } my $start = time; my $nothread = @{ test() }; printf "Unthreaded took: %.6f\n", time() - $start; $start = time; my $thread = @{ threads->create( \&test )->join }; printf "Threaded took: %.6f\n", time() - $start; __END__ c:\test>junk Unthreaded took: 0.000851 Threaded took: 0.012510
The simple solution (for your specific posted example, which isn't using the contents of the AoA, but only the count of elements on the outer array ) ):
say 'Count: ', scalar @{ threads-> create( \&test, 'test.png' )-> join + };
would be to derive the count internal to the function and thus return a scalar rather than a compound data structure:
... shift @b; return scalar @b; }
If your real code actually needs the AoAs returned to the main thread, then show an example of what you are doing with it there and I can perhaps suggest something else.
|
|---|