Ilvsx's Blog

return practice() ? '1 week' : 'never';

用 PHP 读取文件夹大小各路方法哪家强?

参照 Hostker 写在线文件管理器的时候,发现 Hostker 的文件夹也是显示了文件大小的,而且响应速度一点儿也不慢,于是有了下面没什么实际用处的测试。

##测试方法

以发送请求到请求完毕的时间为准

##测试用文件夹

01.jpg

##迭代法

function GetDirectorySize($path){
    $bytestotal = 0;
    $path = realpath($path);
    if($path!==false){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
            $bytestotal += $object->getSize();
        }
    }
    return $bytestotal;
}

02.jpg

##递归大法

function foldersize($path) {
  $total_size = 0;
  $files = scandir($path);

  foreach($files as $t) {
    if (is_dir(rtrim($path, '/') . '/' . $t)) {
      if ($t<>"." && $t<>"..") {
          $size = foldersize(rtrim($path, '/') . '/' . $t);
          $total_size += $size;
      }
    } else {
      $size = filesize(rtrim($path, '/') . '/' . $t);
      $total_size += $size;
    }
  }
  return $total_size;
}

03.jpg

php 调用 linux 命令

function pathsize($path) {
  $io = popen('du -sb ' . $path, 'r');
  $size = fgets($io);
  $pathsize = substr ( $size, 0, strpos ( $size, "\t" ) );
  pclose($io);
  return $pathsize;
}

04.jpg

Python 乱入

from django.http import HttpResponse
import os

path = r'D:\dev\homestead\Code\filem\vendor'
def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size
    
def first_page(request):
    total_size = get_size(path)
    return HttpResponse(total_size)

05.jpg

测试结果

显而易见, 调用系统命令 > 递归 > 迭代