+ 1

How to make WinForm code faster?

I`ve made Convay`s Life Game using winform but its kind of slow.( about 5 generations per second using 30x30 grid ) How can i speed this up? Code: https://www.sololearn.com/compiler-playground/cBNV42zPQ9yk

11th Dec 2022, 10:22 AM
Artur
Artur - avatar
6 Answers
+ 2
For app users, here is the link to the above code: https://code.sololearn.com/cBNV42zPQ9yk/?ref=app Artur possibly Windows is not repainting the screen immediately after it gets changed, so it is skipping frames. Try adding this.Refresh() to the end of your tick event handler.
11th Dec 2022, 5:45 PM
Brian
Brian - avatar
+ 1
Brian , its not skipping frames and repaints just fine, the problem is computing speed. 15x15 field is updating 20 times per second and 50x50 field updates 3-5 times per second. I think its because Get_Neigh() function which is checking every cell, so that's what i want to speed up.
11th Dec 2022, 6:25 PM
Artur
Artur - avatar
+ 1
Hey Artur I revisited this question and was curious to see what ChatGPT (the AI engine) would do to optimize Get_Neigh(). After a couple refinements (and correcting spelling of 'amount'), this is what I came up with. By unrolling the loops, it eliminates some overhead. static int Get_Neigh(in int[,] arr,in int row, in int col) { int amount = 0; if (row > 0 && col > 0) amount += arr[row - 1, col - 1]; if (row > 0) amount += arr[row - 1, col]; if (row > 0 && col < m - 1) amount += arr[row - 1, col + 1]; if (col > 0) amount += arr[row, col - 1]; if (col < m - 1) amount += arr[row, col + 1]; if (row < n - 1 && col > 0) amount += arr[row + 1, col - 1]; if (row < n - 1) amount += arr[row + 1, col]; if (row < n - 1 && col < m - 1) amount += arr[row + 1, col + 1]; return amount; }
4th Jan 2023, 4:50 PM
Brian
Brian - avatar
+ 1
I thought of a further improvement, Artur. I estimate that about 40% of the time is spent checking matrix boundaries. You could eliminate boundary checks by keeping a margin of zeros around the outside of the matrix. In other words, make the boundaries of the game area offset by 1 toward the inside on all edges. Instead of using loop limits of row 0..<n and col 0..<m, the loops would traverse row 1..<n-1 and col 1..<m-1. Then you could optimize Get_Neigh as a one-liner: static int Get_Neigh(in int[,] arr,in int row, in int col) { return arr[row - 1, col - 1] + arr[row - 1, col] + arr[row - 1, col + 1] + arr[row, col - 1] + arr[row, col + 1] + arr[row + 1, col - 1] + arr[row + 1, col] + arr[row + 1, col + 1]; }
4th Jan 2023, 8:22 PM
Brian
Brian - avatar
+ 1
Restart_Array() might be made faster by replacing the nested for loops with Array.Clear(arr, 0, n*m).
8th Jan 2023, 5:52 PM
Brian
Brian - avatar
0
Artur , At line 150 change the value I think this is what you need //timer interval this.timer1.Interval = 100;
11th Dec 2022, 4:45 PM
SoloProg
SoloProg - avatar