| 1 |
# Benchmarking `tsort` |
| 2 |
<!-- spell-checker:ignore (words) randint tsort DAG uu_tsort GNU --> |
| 3 |
Much of what makes `tsort` fast is the efficiency of its algorithm and implementation for topological sorting. |
| 4 |
Our implementation of `tsort` also outputs a cycle whenever such ordering does not exist, just like GNU `tsort`. |
| 5 |
|
| 6 |
## Strategies |
| 7 |
|
| 8 |
To test `tsort`'s performance for its nominal use case, we need to test it with a DAG. One of the worst cases is when all nodes are just representing a succession of independent steps. |
| 9 |
We should also test cycle detection for good measure. |
| 10 |
|
| 11 |
### Random acyclic graph (DAG) |
| 12 |
|
| 13 |
This will output a DAG composed of 1 million pairs of edges between nodes numbered from 0 to 10,000, ensuring that the graph is acyclic by always assigning the edge with the smallest id to the node with the highest one. |
| 14 |
|
| 15 |
```python |
| 16 |
import random |
| 17 |
|
| 18 |
N = 10000 |
| 19 |
|
| 20 |
for i in range(100*N): |
| 21 |
a = random.randint(0, N) |
| 22 |
b = random.randint(0, N) |
| 23 |
print(f"{min(a, b)} {max(a, b)}") |
| 24 |
``` |
| 25 |
|
| 26 |
### Random graph with cycles |
| 27 |
|
| 28 |
The following will output a graph with multiples edges, it also allows some degree of tuning to test different cases. |
| 29 |
|
| 30 |
```python |
| 31 |
import random |
| 32 |
|
| 33 |
# Parameters for the graph |
| 34 |
num_nodes = 100 |
| 35 |
num_edges = 150 |
| 36 |
cycle_percentage = 0.10 |
| 37 |
max_cycle_size = 6 |
| 38 |
|
| 39 |
num_cycles = int(num_edges * cycle_percentage) |
| 40 |
|
| 41 |
for _ in range(num_edges - num_cycles): |
| 42 |
a = random.randint(0, num_nodes) |
| 43 |
b = random.randint(0, num_nodes) |
| 44 |
print(f"{a} {b}") |
| 45 |
|
| 46 |
|
| 47 |
for _ in range(num_cycles): |
| 48 |
cycle_size = random.randint(3, max_cycle_size) |
| 49 |
cycle_nodes = random.sample(range(num_nodes), cycle_size) |
| 50 |
for i in range(cycle_size): |
| 51 |
print(f"{cycle_nodes[i]} {cycle_nodes[(i + 1) % cycle_size]}") |
| 52 |
``` |
| 53 |
|
| 54 |
## Running Benchmarks |
| 55 |
The above scripts will output the generated graphs to the standard output. They can therefore be used directly as tests. In order to run a Benchmark, the output should be redirected to a file. |
| 56 |
Use [`hyperfine`](https://github.com/sharkdp/hyperfine) to compare the performance of different `tsort` versions. For example, you can compare the performance of GNU `tsort` and another implementation with the following command: |
| 57 |
|
| 58 |
```sh |
| 59 |
hyperfine 'tsort random_graph.txt' 'uu_tsort random_graph.txt' |
| 60 |
``` |
| 61 |
|
| 62 |
## Note |
| 63 |
|
| 64 |
Benchmark results from the above scripts are fuzzy and change from run to run unless a seed is set. |