我有三个函数:_sort、_strpos、_array_int
<?php
class timer{
private $_start;
private $_end;
public function program_begin(){
$this->_start = microtime(true);
}
public function program_end(){
$this->_end = microtime(true);
}
public function get_time(){
$time_use = ($this->_end - $this->_start)*1000;
echo $time_use."ms\n";
}
};
$t = new timer();
$test_cnt = $argv[1];
$s_len1 = $s_len2 = $argv[2];
$t->program_begin();
for($j = 0; $j<$test_cnt; $j++){
for($i = 0; $i < $s_len1; $i++)
$s1 .= chr(rand()%26+97);
for($i = 0; $i < $s_len2; $i++)
$s2 .= chr(rand()%26+97);
$flag = call_user_func($argv[3],$s1, $s2);
$s1=$s2="";
}
$t->program_end();
$t->get_time();
function _sort($s1, $s2){
for($i = 0; $i < strlen($s1); $i++)
$arr[] = $s1[$i];
sort($arr);
for($i = 0; $i < strlen($s2); $i++)
if(!search_part($arr, $s2[$i]))
return false;
return true;
}
function search_part($arr, $key){
$s = 0;
$e = count($arr)-1;
while($s<=$e){
$m = (int)(($s+$e)/2);
if($arr[$m] > $key)
$e = $m-1;
if($arr[$m] < $key)
$s = $m+1;
if($arr[$m] == $key)
return true;
}
return false;
}
function _strpos($s1, $s2){
for($i = 0; $i < strlen($s2); $i++)
if(strpos($s1,$s2[$i]) === false)
return false;
return true;
}
function _array($s1, $s2){
for($i = 0; $i < strlen($s1); $i++)
$arr[$s1[$i]] = 1;
for($i = 0; $i < strlen($s2); $i++)
if(!isset($arr[$s2[$i]]))
return false;
return true;
}
function _array_int($s1,$s2){
for($i = 0; $i < strlen($s1); $i++)
$arr[ord($s1[$i])] = 1;
for($i = 0; $i < strlen($s2); $i++)
if(!isset($arr[ord($s2[$i])]))
return false;
return true;
}
我认为时间复杂度:
_sort(as func A) : O(nlgn)
_array_int(as func B): O(n)
_strpos(as func C): O(n^2)
因此速度似乎是B>A> C
但测试结果是:C>B>A
我无法解释为什么 C 最快。
像这样测试它php test.php test_count word_lenght test_func