Easier to do it yourself, or to fork () or not to fork ()

    Solving the problem of calculating volumetric data in cycles often pulls to parallelize the problem.
    Of course, in perl there are just a couple of models: fork or thread, which allow the use of "multithreading". The implementation of each method and religious preferences do not apply to the material in this note.
    We will talk about reinforcing the choice of “share / not share” with numbers.

    In short, the separation of the computation into a “separate stream”, in addition to the pluses, also has a fat minus associated with the overhead of creating a descendant, communicating with him and maintaining it.
    It is logical to assume that knowing the cost of the overhead of "multithreading" we can reasonably choose one or another architecture of our application. So you need to take and calculate, for example, like this:

    use Benchmark qw( timethese cmpthese ) ;

    sub forked {
      my $pid = fork;
      $pid ? waitpid($pid, 0) : exit 0;

    sub empty {

    my $r = timethese( -1, {
        a => sub {forked(2)},
        b => sub{empty(2)},
      } );
    cmpthese $r;

    * This source code was highlighted with Source Code Highlighter.

    As a result of a simple action, we get something like:

    Benchmark: running a, b for at least 1 CPU seconds...
         a: 7 wallclock secs ( 0.09 usr 0.96 sys + 1.93 cusr 3.45 csys = 6.43 CPU) @ 278.69/s (n=1792)
         b: 2 wallclock secs ( 1.11 usr + 0.01 sys = 1.12 CPU) @ 2730666.07/s (n=3058346)
        Rate    a    b
    a   279/s   --  -100%
    b 2730666/s 979709%   --

    * This source code was highlighted with Source Code Highlighter.

    Well, that means the thread creation cycle and its maintenance gives us a maximum performance of 278.69 / s . This means that any calculation that is performed faster we consider ourselves, and all the more cumbersome - we give to the children!
    You should often use the benchmark where the numbers allow you to draw conclusions and make the right decision.

    Also popular now: