Created
January 26, 2025 04:31
-
-
Save arsdragonfly/3b9eec33918dc3c8bcec95ce7dc4cd9f to your computer and use it in GitHub Desktop.
game of life Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #[bench] | |
| fn game_of_life(b: &mut Bencher) { | |
| // naive Vec implementation | |
| const size_board_side: usize = 1024 * 8; | |
| // 1d vec | |
| let mut board = vec![0u8; size_board_side * size_board_side]; | |
| let mut next_state: Vec<u8> = vec![0; size_board_side * size_board_side]; | |
| // random initialization | |
| // outermost ring is invalid | |
| for i in 1..size_board_side - 1 { | |
| for j in 1..size_board_side - 1 { | |
| board[i * size_board_side + j] = rand::random(); | |
| } | |
| } | |
| b.iter(|| { | |
| for _ in 0..1 { | |
| for i in 1..size_board_side - 1 { | |
| for j in 1..size_board_side - 1 { | |
| // add to counter positions corresponding to board[i][j] | |
| let idx = i * size_board_side + j; | |
| let mut count = 0; | |
| count += board[(i - 1) * size_board_side + j - 1]; | |
| count += board[(i - 1) * size_board_side + j]; | |
| count += board[(i - 1) * size_board_side + j + 1]; | |
| count += board[i * size_board_side + j - 1]; | |
| count += board[i * size_board_side + j + 1]; | |
| count += board[(i + 1) * size_board_side + j - 1]; | |
| count += board[(i + 1) * size_board_side + j]; | |
| count += board[(i + 1) * size_board_side + j + 1]; | |
| next_state[idx] = match (board[idx], count) { | |
| (1, 2) | (1, 3) => 1, | |
| (0, 3) => 1, | |
| _ => 0, | |
| }; | |
| } | |
| } | |
| std::mem::swap(&mut next_state, &mut board); | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment