File tree 2 files changed +44
-0
lines changed
2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ #![ feature( test) ]
2
+ extern crate test;
1
3
extern crate libc;
4
+
2
5
use libc:: c_char;
3
6
use std:: ffi:: CString ;
4
7
use std:: iter;
@@ -27,4 +30,40 @@ pub extern fn text_free(s: *mut c_char) {
27
30
if s. is_null ( ) { return }
28
31
CString :: from_raw ( s)
29
32
} ;
33
+ }
34
+
35
+ // rust生成
36
+ fn rust_text_generate ( length : u8 ) -> String {
37
+ let mut song = String :: from ( "💣" ) ;
38
+ song. extend ( iter:: repeat ( "na " ) . take ( length as usize ) ) ;
39
+ song. push_str ( "Batman! 💣" ) ;
40
+
41
+ song
42
+ }
43
+
44
+ // cargo +nightly bench
45
+ #[ cfg( test) ]
46
+ mod tests {
47
+ use super :: * ;
48
+ use test:: Bencher ;
49
+
50
+ #[ test]
51
+ fn test_rust_text_generate ( ) {
52
+ assert_eq ! ( rust_text_generate( 12 ) , "💣na na na na na na na na na na na na Batman! 💣" ) ;
53
+ }
54
+
55
+ #[ bench]
56
+ fn bench_text_generate ( b : & mut Bencher ) {
57
+ b. iter ( || {
58
+ let result = text_generate ( 12 ) ;
59
+ text_free ( result) ;
60
+ } ) ;
61
+ }
62
+
63
+ #[ bench]
64
+ fn bench_rust_text_generate ( b : & mut Bencher ) {
65
+ b. iter ( || {
66
+ let _ = rust_text_generate ( 12 ) ;
67
+ } ) ;
68
+ }
30
69
}
Original file line number Diff line number Diff line change 23
23
$ result = FFI ::string ($ rstr ); // 转成php字符串
24
24
$ ffiDebug ->text_free ($ rstr ); // 释放掉内存
25
25
}
26
+ // debug在8300ns一次
26
27
echo '[Rust]debug执行时间: ' . (microtime (true ) - $ time_start ).PHP_EOL ;
27
28
var_dump ($ result );
28
29
38
39
$ result = FFI ::string ($ rstr ); // 转成php字符串
39
40
$ ffiRelease ->text_free ($ rstr ); // 释放掉内存
40
41
}
42
+ // release基本上在1600ns一次
43
+ // 测试在rust中每次操作在700ns一次,那就是这里的FFI转值消耗了将近1000ns
41
44
echo '[Rust]release执行时间: ' . (microtime (true ) - $ time_start ).PHP_EOL ;
42
45
var_dump ($ result );
43
46
@@ -53,8 +56,10 @@ function text_generate($num) {
53
56
54
57
$ time_start = microtime (true );
55
58
for ($ i =0 ; $ i < 1000000 ; $ i ++) {
59
+ $ result = "" ;
56
60
$ result = text_generate (12 );
57
61
}
62
+ // 这里计算出PHP这样一个生成字符串的操作,实际是需要270ns左右
58
63
echo '[PHP]执行时间: ' . (microtime (true ) - $ time_start ).PHP_EOL ;
59
64
var_dump ($ result );
60
65
?>
You can’t perform that action at this time.
0 commit comments