创建与复制空文件,哪种操作成本最低


Create vs Copy empty file, which operation is the least expensive?

哪种方法在服务器上最便宜?我正在动态创建目录,希望每个目录都包含一个空的html文件。此外,如何衡量差异?

$file = text.html;
$newDest = myDir/text.html;
copy($file, $newDest);

$File = "myDir/text.html"; 
$Handle = fopen($File, 'w');
$Data = ''; 
fwrite($Handle, $Data);  
print "Data Written"; 
fclose($Handle); 

touch和file_put_contents几乎相同。它们以相同的速度下降。我用以下函数做了一些基准测试。

define('MAX_ITERATION', 10000);
function create_empty_fpc($name) {
    file_put_contents(dirname(__FILE__)."/create_fpc/$name", "");
}
function create_empty_fopen($name) {
    if($fh=fopen(dirname(__FILE__)."/create_fopen/$name", "w"))
    fclose($fh);
}
function copy_empty($name) {
    copy(dirname(__FILE__).'/empty', dirname(__FILE__)."/copy/$name");
}
function touch_empty($name){
    touch(dirname(__FILE__)."/touch/$name");
}

结果

+-------------------------+---------------------------+
| Script name             | Execution time in seconds |
+-------------------------+---------------------------+
| With create_empty_fopen | 1.4960081577301           |
| With create_empty_fpc   | 1.2142379283905           |
| With copy_empty         | 1.4280989170074           |
| With touch_empty        | 1.0558199882507           |
+-------------------------+---------------------------+

结论

触摸是最快的。在该文件之后_put_contents。复制和只创建一个空文件的速度几乎相同。

由于各种原因,复制操作通常非常昂贵。我每运行1000次以下操作进行比较:
 copy
 touch
 fopen, fwrite, fclose
 fopen, fclose //this still creates the file
 fopen //files closed automatically, but this may take up more memory.

CCD_ 1的速度始终是任何CCD_ 2方法的两倍(所有方法的速度都大致相同)。CCD_ 3始终是最慢的。

就内存而言,fopen可能使用更多,因为您必须存储文件句柄,而touchcopy只返回布尔值。

总之,使用touch

我相信这将是最便宜的:

$file = "path/filename.html";
touch($file)
  or die("Error creating '$file'.'n");
echo "'$file' created'n";

如何测量差异:

测量代码的执行时间称为评测,使用分析器完成。可选的xdebug模块提供了评测。

在紧要关头,你可以尝试直接在PHP中测量它,这样:

$start = time();
// ...
$end = time();
$executionSeconds = $end - $start;
echo "Completed in $executionSeconds seconds.";

注意:我不认为这会特别准确或有用。使用探查器是您的最佳选择。