Skip to content

Commit 089c0a5

Browse files
author
llgoer
committed
完善字符串测试
1 parent c8aef93 commit 089c0a5

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

r2p-fib/src/lib.rs

+39
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
#![feature(test)]
2+
extern crate test;
13
extern crate libc;
4+
25
use libc::c_char;
36
use std::ffi::CString;
47
use std::iter;
@@ -27,4 +30,40 @@ pub extern fn text_free(s: *mut c_char) {
2730
if s.is_null() {return}
2831
CString::from_raw(s)
2932
};
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+
}
3069
}

test-ffi2.php

+5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
$result = FFI::string($rstr); // 转成php字符串
2424
$ffiDebug->text_free($rstr); // 释放掉内存
2525
}
26+
// debug在8300ns一次
2627
echo '[Rust]debug执行时间:' . (microtime(true) - $time_start).PHP_EOL;
2728
var_dump($result);
2829

@@ -38,6 +39,8 @@
3839
$result = FFI::string($rstr); // 转成php字符串
3940
$ffiRelease->text_free($rstr); // 释放掉内存
4041
}
42+
// release基本上在1600ns一次
43+
// 测试在rust中每次操作在700ns一次,那就是这里的FFI转值消耗了将近1000ns
4144
echo '[Rust]release执行时间:' . (microtime(true) - $time_start).PHP_EOL;
4245
var_dump($result);
4346

@@ -53,8 +56,10 @@ function text_generate($num) {
5356

5457
$time_start = microtime(true);
5558
for ($i=0; $i < 1000000; $i++) {
59+
$result = "";
5660
$result = text_generate(12);
5761
}
62+
// 这里计算出PHP这样一个生成字符串的操作,实际是需要270ns左右
5863
echo '[PHP]执行时间:' . (microtime(true) - $time_start).PHP_EOL;
5964
var_dump($result);
6065
?>

0 commit comments

Comments
 (0)