BillKSmith has asked for the wisdom of the Perl Monks concerning the following question:
My goal is to compute and set the color of every pixel in a 500x500 image. Placing the entire computation in a single call back leaves my machine unresponsive for fifteen to thirty seconds. The only solution that I could think of was to compute one row of pixels at a time. Here is a demo of my implementation:
use strict; use warnings; use v5.14; use Tk; my $mw = new MainWindow( -title => 'Event demo'); my $drawarea = $mw->Frame()->pack( -side => 'top', -fill => 'both' ); $mw->bind('<<RowDone>>' => \&next_row); my $p = $mw->Photo(-width=>500, -height=>500); my $canvas = $drawarea->Canvas( -relief => 'ridge', -width => 500, -height => 500, -borderwidth => 4 )->pack(); $canvas->bind('<<RowDone>>' => \&next_row); $canvas->createImage(0,0, -anchor=>'nw', image=>$p); my $plot = $mw->Button(-text=>'Plot', -command=>\&init) ->pack(-side=>'left'); MainLoop; # Callbacks sub init { our $y = 0; $mw->eventGenerate('<<RowDone>>'); return; } sub next_row { our $y; for my $x ( 0..499 ) { my $quality = long_computation($x, $y); $p->put(color($quality), '-to', $x, $y); } $canvas->update; if (++$y < 500) { $mw->eventGenerate('<<RowDone>>', -when => 'tail' ); } return; } # stubs for demo only sub color { return 'red' } sub long_computation { return 10; }
This works as intended, but brings up some new issues.
The current row number ($y) must be declared globally with 'our'. I would prefer to pass a lexical value from one iteration to the next through the event structure. I have not been able to find a way to do this.
There does not seem to be any way to cancel a calculation in progress. I am unable to cancel a <<RowDone>> event which is already scheduled (or soon will be).
This is very likely an X-Y problem. I am interested in better solutions to the original problem as well as improvements to my solution.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: long computation in TK
by choroba (Cardinal) on Jun 25, 2018 at 16:31 UTC | |
|
Re: long computation in TK
by zentara (Cardinal) on Jun 26, 2018 at 10:33 UTC | |
|
Re: long computation in TK
by bliako (Abbot) on Jun 25, 2018 at 18:46 UTC | |
|
Re: long computation in TK
by Anonymous Monk on Jun 25, 2018 at 18:24 UTC | |
by Marshall (Canon) on Jun 26, 2018 at 08:51 UTC | |
by Corion (Patriarch) on Jun 26, 2018 at 08:55 UTC | |
by Anonymous Monk on Jun 26, 2018 at 12:55 UTC | |
by Marshall (Canon) on Jun 27, 2018 at 20:30 UTC | |
by BillKSmith (Monsignor) on Jun 26, 2018 at 19:03 UTC | |
|
Re: long computation in TK
by BillKSmith (Monsignor) on Jun 26, 2018 at 19:45 UTC | |
by zentara (Cardinal) on Jun 27, 2018 at 20:36 UTC | |
by BillKSmith (Monsignor) on Jun 28, 2018 at 12:42 UTC |