Hi all
I’m back to processing. I was using this tool when i was student 10 years ago, and its really pleasure to re-use it !
I’m triyng to use Kinect to generate design and im working to calculate pixels data evolutions, that mean i need to use long multiple array treatment… This work make slowdown my screenview… Anyone know a Library or a tips to improve performance ?
Thank you !!
Most of the time it’s done using Multithreading which works by breaking your problem into smaller ones and solving them in parallel in different threads.
I don’t know the internals of how your algorithm works but you can also find ways to improve efficiency with programming / algorithmic tricks. (choosing the right data structures, avoid cache misses and useless memory allocations…)
The Processing thread() function is a wrapper for easily creating a Thread instance that launches a method defined earlier. (see the actual code here).
What you need to do is to break your image into square tiles, one for each thread, do the computation of each specific tile and then wait for all the threads to finish.
This is an example by extending the Thread class and assigning a random color for each time:
class TileThread extends Thread {
int x, y, w, h;
color randomColor;
TileThread(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
randomColor = color(random(255), random(255), random(255));
}
void run() {
for (int i = x; i < x + w; i++) {
for (int j = y; j < y + h; j++) {
int loc = i + width * j;
pixels[loc] = randomColor;
}
}
}
}
int nTiles = 5;
void setup() {
size(500, 500);
}
void draw() {
int tileSizeX = width / nTiles;
int tileSizeY = height / nTiles;
ArrayList<Thread> tileThreads = new ArrayList();
loadPixels();
// Create one thread for each square tile (like a grid)
for (int i = 0; i < nTiles; i++) {
int x = i * tileSizeX;
for (int j = 0; j < nTiles; j++) {
int y = j * tileSizeY;
Thread thread = new TileThread(x, y, tileSizeX, tileSizeY);
thread.run();
tileThreads.add(thread);
}
}
// Wait for all the threads to finish
for (Thread thread : tileThreads) {
try {
thread.join();
} catch (InterruptedException e) {
println(e);
}
}
updatePixels();
}
(this works when the canvas size is divisible by nTiles but you can support non square tiles)
(be careful not to modify the same tiles from two different threads leading to a race condition)
Hi Josehh! Thank you for your answer
Yes i was trying with Thread, but it was impossible to send var to the Thread, maybe this way would be better for me, I’ll try and decompose this to understand, thank you very munch !!