Last active
January 26, 2025 04:30
-
-
Save arsdragonfly/2dc9be2adc986bc5fa067b9757f85558 to your computer and use it in GitHub Desktop.
game of life cuDF
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
| # game of life | |
| import cupy as cp | |
| import cudf | |
| import time | |
| dim_x = 1024 * 8 | |
| dim_y = 1024 * 8 | |
| df = cudf.DataFrame({ | |
| # x y indices and bool | |
| "x": cp.arange(0, dim_x, dtype=cp.uint32).repeat(dim_y), | |
| "y": cp.tile(cp.arange(0, dim_y, dtype=cp.uint32), dim_x), | |
| "alive": cp.random.choice([0, 1], size=dim_x * dim_y), | |
| "n_alive": cp.zeros(dim_x * dim_y, dtype=cp.uint8) | |
| }) | |
| print(df) | |
| # iterate game of life | |
| time_start = time.perf_counter_ns() | |
| for _ in range(100): | |
| # count neighbors | |
| df["n_alive"] = ( | |
| df["alive"].shift(-1, fill_value=0) + | |
| df["alive"].shift(1, fill_value=0) + | |
| df["alive"].shift(-dim_x, fill_value=0) + | |
| df["alive"].shift(dim_x, fill_value=0) + | |
| df["alive"].shift(-dim_x - 1, fill_value=0) + | |
| df["alive"].shift(-dim_x + 1, fill_value=0) + | |
| df["alive"].shift(dim_x - 1, fill_value=0) + | |
| df["alive"].shift(dim_x + 1, fill_value=0) | |
| ) | |
| # apply game of life rules | |
| df["alive"] = ( | |
| ((df["alive"] == 1) & ((df["n_alive"] == 2) | (df["n_alive"] == 3)) | | |
| (df["alive"] == 0) & (df["n_alive"] == 3)) | |
| ).astype(cp.uint8) | |
| # outermost cells are invalid and shall always be zero | |
| df["alive"][0:dim_x] = cp.uint8(0) | |
| df["alive"][-dim_x:] = cp.uint8(0) | |
| df["alive"][::dim_x] = cp.uint8(0) | |
| df["alive"][dim_x - 1::dim_x] = cp.uint8(0) | |
| time_end = time.perf_counter_ns() | |
| print(df) | |
| print(df["alive"].sum()) | |
| print(f"Execution Time: {time_end - time_start} ns") | |
| print(f"Execution Time per cell per iteration: {float(time_end - time_start) / dim_x / dim_y / 100} ns") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment