1
- use cpython:: Python ;
2
1
use criterion:: measurement:: WallTime ;
3
2
use criterion:: {
4
3
criterion_group, criterion_main, BatchSize , BenchmarkGroup , BenchmarkId , Criterion , Throughput ,
@@ -19,31 +18,29 @@ pub struct MicroBenchmark {
19
18
20
19
fn bench_cpython_code ( group : & mut BenchmarkGroup < WallTime > , bench : & MicroBenchmark ) {
21
20
let gil = cpython:: Python :: acquire_gil ( ) ;
22
- let python = gil. python ( ) ;
21
+ let py = gil. python ( ) ;
23
22
24
- let bench_func = |( python , code ) : ( Python , String ) | {
25
- let res: cpython :: PyResult < ( ) > = python . run ( & code, None , None ) ;
23
+ let bench_func = |( globals , locals ) | {
24
+ let res = py . run ( & bench . code , Some ( & globals ) , Some ( & locals ) ) ;
26
25
if let Err ( e) = res {
27
- e. print ( python ) ;
26
+ e. print ( py ) ;
28
27
panic ! ( "Error running microbenchmark" )
29
28
}
30
29
} ;
31
30
32
31
let bench_setup = |iterations| {
33
- let code = if let Some ( idx) = iterations {
34
- // We can't easily modify the locals when running cPython. So we just add the
35
- // loop iterations at the top of the code...
36
- format ! ( "ITERATIONS = {}\n {}" , idx, bench. code)
37
- } else {
38
- ( & bench. code ) . to_string ( )
39
- } ;
32
+ let globals = cpython:: PyDict :: new ( py) ;
33
+ let locals = cpython:: PyDict :: new ( py) ;
34
+ if let Some ( idx) = iterations {
35
+ globals. set_item ( py, "ITERATIONS" , idx) . unwrap ( ) ;
36
+ }
40
37
41
- let res: cpython :: PyResult < ( ) > = python . run ( & bench. setup , None , None ) ;
38
+ let res = py . run ( & bench. setup , Some ( & globals ) , Some ( & locals ) ) ;
42
39
if let Err ( e) = res {
43
- e. print ( python ) ;
40
+ e. print ( py ) ;
44
41
panic ! ( "Error running microbenchmark setup code" )
45
42
}
46
- ( python , code )
43
+ ( globals , locals )
47
44
} ;
48
45
49
46
if bench. iterate {
0 commit comments