吃饱喝足了,还发贴了。
拆开分成几千份进行排序再合并。
首先先创建一个1亿个QQ号的txt。
- PHP code
$v)
{
$arr = range($v*10000+10000,10000*($v+1)+9999);
shuffle($arr);
fputs($fp,implode("\n", $arr)."\n");
unset($arr);
}
echo microtime(true)-$st;
?>
稍等一两分钟1亿个随机QQ创建完成了。
QQ号码范围为>10000。文件大小大概有840MB。
下面就进行分类划分成几千份文件。
以QQ号码长度为文件夹,QQ号码前3位为文件名。
- PHP code
$v)
{
if($v!='')
{
$tag = "$v[0]$v[1]$v[2]";
$text_arr[strlen($v)][$tag][] = $v;
}
}
foreach ($text_arr as $k=>$v)
{
$n_dir = 'qq_no/'.$k;
if (!is_dir($n_dir)) mkdir($n_dir);
foreach ($v as $tag=>$val)
{
$n_tf = fopen($n_dir.'/'.$tag.'.txt', 'a+');
fputs($n_tf,implode("\n",$val)."\n");
}
}
unset($text_arr);
++$i;
}
echo microtime(true)-$st;
?>
最后就要每个文件进行排序合并数据了。
- PHP code
$val)
{
if ($val != '.' && $val != '..')
$dirs[$val] = scandir($root.'/'.$val);
}
foreach ($dirs as $key=>$val)
{
foreach ($val as $v)
{
if ($v != '.' && $v != '..')
{
$file = $root. '/' . $key . '/'. $v;
$c = file_get_contents($file);
$arr = explode("\n", $c);
sort($arr);
fputs($qq_done, implode("\n",$arr));
unlink($file);
}
}
rmdir($root. '/' . $key);
}
rmdir($root);
echo microtime(true)-$st;
?>
总共大概花费了20多分钟。
虽然完成了,但方法很土鳖 0_0 ,坛里各位高手们改进改进啊。
------解决方案--------------------
来个C版本的
- C/C++ code
#include#define BITSPERWORD 32 #define SHIFT 5 #define MASK 0x1F #define N 100000000 int a[1 + N/BITSPERWORD]; void set(int i) { a[i>>SHIFT] |= (1<<(i & MASK)); //i&MASK相当于1&(32-1),即1%32 } void clr(int i) { a[i>>SHIFT] &= ~(1<<(i & MASK)); } int test(int i) { return a[i>>SHIFT] & (1<<(i & MASK)); } int main() { int i; //初始化 for(i = 0; i < N; i++) clr(i); //读取文件,置位 while(scanf("%d", &i) != EOF) set(i); for(i = 0; i < N; i++) if(test(i)) printf("%d\n", i); return 0; }
------解决方案--------------------
既然有现成的数据文件,就没有必要去构造插入串了PHP code
set_time_limit(0); $sql =<<< SQL CREATE TABLE IF NOT EXISTS qq1 ( `qq` int(10) NOT NULL, KEY `qq` (`qq`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; SQL; mysql_connect('localhost', 'root', ''); mysql_select_db('test'); mysql_query($sql); $filename = str_replace('\\', '/', realpath('qq.txt')); $sql =<<< SQL LOAD DATA INFILE '$filename' INTO TABLE qq1 SQL; check_speed(1); mysql_query($sql) or print(mysql_error());; check_speed();