File: bellman_ford.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (60 lines) | stat: -rw-r--r-- 1,755 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#![feature(test)]

extern crate petgraph;
extern crate test;

use petgraph::prelude::*;
use std::cmp::{max, min};
use test::Bencher;

use petgraph::algo::{bellman_ford, find_negative_cycle};

#[bench]
fn bellman_ford_bench(bench: &mut Bencher) {
    static NODE_COUNT: usize = 100;
    let mut g = Graph::new();
    let nodes: Vec<NodeIndex<_>> = (0..NODE_COUNT).map(|i| g.add_node(i)).collect();
    for i in 0..NODE_COUNT {
        let n1 = nodes[i];
        let neighbour_count = i % 8 + 3;
        let j_from = max(0, i as i32 - neighbour_count as i32 / 2) as usize;
        let j_to = min(NODE_COUNT, j_from + neighbour_count);
        for j in j_from..j_to {
            let n2 = nodes[j];
            let mut distance: f64 = ((i + 3) % 10) as f64;
            if n1 != n2 {
                distance -= 1.0
            }
            g.add_edge(n1, n2, distance);
        }
    }

    bench.iter(|| {
        let _scores = bellman_ford(&g, nodes[0]);
    });
}

#[bench]
fn find_negative_cycle_bench(bench: &mut Bencher) {
    static NODE_COUNT: usize = 100;
    let mut g = Graph::new();
    let nodes: Vec<NodeIndex<_>> = (0..NODE_COUNT).map(|i| g.add_node(i)).collect();
    for i in 0..NODE_COUNT {
        let n1 = nodes[i];
        let neighbour_count = i % 8 + 3;
        let j_from = max(0, i as i32 - neighbour_count as i32 / 2) as usize;
        let j_to = min(NODE_COUNT, j_from + neighbour_count);
        for j in j_from..j_to {
            let n2 = nodes[j];
            let mut distance: f64 = ((i + 3) % 10) as f64;
            if n1 != n2 {
                distance -= 1.0
            }
            g.add_edge(n1, n2, distance);
        }
    }

    bench.iter(|| {
        let _scores = find_negative_cycle(&g, nodes[0]);
    });
}