【发布时间】:2011-05-02 09:49:01
【问题描述】:
我有一堆文件需要处理,我担心可扩展性和速度。
文件名和文件数据(仅第一行)存储在 RAM 中的一个数组中,以便稍后在脚本中创建一些静态文件。 文件必须是文件,不能放入数据库中。
文件名的格式如下: Y-M-D-title.ext(其中 Y 为年,M 为月,D 为日)
我实际上是在使用 glob 列出所有文件并创建我的数组: 这是创建数组“for year”或“month”的代码示例(它用于只有一个参数的函数 -> $period)
[...]
function create_data_info($period=NULL){
$data = array();
$files = glob(ROOT_DIR.'/'.'*.ext');
$size = sizeOf($files);
$existing_title = array(); //Used so we can handle having the same titles two times at different date.
if (isSet($period)){
if ( "year" === $period ){
for ($i = 0; $i < $size; $i++) {
$info = extract_info($files[$i], $existing_file);
//Create the data array with all the data ordered by year/month/day
$data[(int)$info[5]][] = $info;
unset($info);
}
}elseif ( "month" === $period ){
for ($i = 0; $i < $size; $i++) {
$info = extract_info($files[$i], $existing_file);
$key = $info[5].$info[6];
//Create the data array with all the data ordered by year/month/day
$data[(int)$key][] = $info;
unset($info);
}
}
}
[...]
}
function extract_info($file, &$existing){
$full_path_file = $file;
$file = basename($file);
$info_file = explode("-", $file, 4);
$filetitle = explode(".", $info_file[3]);
$info[0] = $filetitle[0];
if (!isSet($existing[$info[0]]))
$existing[$info[0]] = -1;
$existing[$info[0]] += 1;
if ($existing[$info[0]] > 0)
//We have already found a post with this title
//the creation of the cache is based on info[4] data for the filename
//so we need to tune it
$info[0] = $info[0]."-".$existing[$info[0]];
$info[1] = $info_file[3];
$info[2] = $full_path_file;
$post_content = file(ROOT_DIR.'/'.$file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$info[3] = $post_content[0]; //first line of the files
unset($post_content);
$info[4] = filemtime(ROOT_DIR.'/'.$file);
$info[5] = $info_file[0]; //year
$info[6] = $info_file[1]; //month
$info[7] = $info_file[2]; //day
return $info;
}
所以在我的脚本中,我只调用 create_data_info(PERIOD) (PERIOD 是“年”、“月”等)
它返回一个包含我需要的信息的数组,然后我可以循环遍历它来创建我的统计文件。 每次启动 PHP 脚本时都会执行此过程。
我的问题是:这段代码是最优的(当然不是),我该怎么做才能从我的代码中榨取一些汁液? 我不知道如何缓存它(即使可能),因为涉及到很多 I/O。
如果树结构与平面结构相比可以改变一些东西,我可以改变它,但从我的测试中发现,它似乎是最好的。
我已经考虑过在 C 中创建一个小“助推器”,只做运算,但我认为它是 I/O 绑定的,我认为它不会产生巨大的差异,并且应用程序的兼容性会大大降低共享主机用户。
非常感谢您的意见,我希望我在这里已经足够清楚了。如果您需要澄清,请告诉我(忘记我的英语错误)。
【问题讨论】:
-
你不清楚,代码也不清楚。删除与问题无关的代码,并尝试更好地解释应该发生的事情。
-
我重写了我的问题,希望这次更清楚。
-
如果您不经常添加数据并且经常调用 create_data_info,那么您可以考虑为每个 PERIOD 创建缓存文件。不要认为 C 助推器会有帮助,因为 glob 已经在使用 libc。
-
是的,我正在考虑,但不知道如何:/。我知道缓存数据库,但不知道将每个 PERIOD 信息缓存到文件中。