插入10W数据的两个程序比较

程序1 添加10W数据

$count = 0;
for ($i = 1;$i <= 100000 ;$i++) {
    $add_data = [
        'id'       => $i,
        'username' => 'user'.$i,
        'sex'      => mt_rand(1,2),
        'age'      => mt_rand(10,60),
    ];

    $res = Db::connect('db_test')->table('tf_user')->insert($add_data);
    if ($res) {
        $count ++ ;
        Clog::setLog('成功添加'.$i."条","add_user");
    }
}
$this->json->setAttr('data',"成功添加".$count."个数据。");
$this->json->Send();

10W条数据,用时近85分钟。上面的代码,需要的内存少一些。执行的时间比较久。

程序2 添加10W数据

$all_data = [];
Clog::setLog("开始生成","add_user");
$begin = 100001;
$end   = 200000;
$count = 0;
$total_count = 0;
for ($i = $begin;$i <= $end ;$i++) {
    $add_data = [
        'id'       => $i,
        'username' => 'user'.$i,
        'sex'      => mt_rand(1,2),
        'age'      => mt_rand(10,60),
    ];
    $all_data[] = $add_data;
    if (count($all_data) == 10000) {
        $count = Db::connect('db_test')->table('tf_user')->insertAll($all_data);
        $total_count += $count;
        $all_data = []; // 重置
    }
}

Clog::setLog('完成添加'.$total_count."条","add_user");
$this->json->setAttr('data',"成功添加".$total_count."个数据。");
$this->json->Send();
}

用时不到6分钟。
insertAll 方法生成的sql。

INSERT INTO `tf_user` (`id` , `username` , `sex` , `age`) VALUES ( 100001,'user100001',2,47 ) , ( 100002,'user100002',2,26 ) , ( 100003,'user100003',1,10 ) , ( 100004,'user100004',2,10 ) , ( 100005,'user100005',2,50 )

两个程序用时差距如此之大,数据量小看不出来,数据量大就能看出来了。第二个程序明显用时快了很多,但是需要的内存会大一些。

修改php.ini之后,重启php-fpm才能生效。重新加载nginx是没有效果的。

service php-fpm restart

修改my.cnf

sudo vim /etc/my.cnf 

重启

service mysql restart

猜你喜欢

转载自www.cnblogs.com/jiqing9006/p/10130564.html