PHP&压力测试 - 将大文件加载到内存中

时间:2014-02-07 11:58:43

标签: php

我必须使用Apache Benchmark对URL(PHP脚本)进行压力测试。但是对于每个请求,我需要处理一组不同的数据,并且URL保持不变。所以在PHP脚本中我需要读取3.000.000行文件并随机选择一个。这意味着对于每个ab请求,我需要读取该文件,然后得到一个随机行,然后处理它。

您推荐什么方法?

我想以某种方式将该文件加载到内存中一次(并且可用于所有请求),然后从中获取随机行。

换句话说,我需要从一个大文件中读取一个随机行而不“感觉”它。

谢谢!

1 个答案:

答案 0 :(得分:1)

$fh    = fopen($file, 'r');
$stats = fstat($fh);

// jump to random location within file
fseek($fh, mt_rand(0, $stats['size'] - 1));

// check where you are    
$chr = fread($fh, 1);

// while you're not at a newline and not at the start of the file
while ($chr != "\n" && ftell($fh) > 0) {
    // go back one character (plus an additional one you've just read)
    fseek($fh, -2, SEEK_CUR);
    $chr = fread($fh, 1);
}

// you're just past a newline now, go read the whole next line
$line = fgets($fh);