PHP 插入大数据优化

    /*public function index()
    {
        set_time_limit(0);

        $time1 = microtime(true);

        for ($i=200001; $i<300000; $i++) {

            $sql = "insert into think_test(name) values ($i)";
            Db::query($sql);

        }

        $time2 = microtime(true);

        echo $time1-$time2; //42.355000019073s
    }*/

    public function index()
    {
        set_time_limit(0);

        $time1 = microtime(true);

        $sql = "insert into think_test(name) values ";
        for ($i=0; $i<1000000; $i++) {

            $sql .= "($i),";
        } //insert into think_test(name) values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),

        //insert into think_test(name) values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)
        $sql = substr($sql, 0, -1);

        Db::query($sql);

        $time2 = microtime(true);

        echo $time2-$time1; //5s
    }

    /**
     *
     * @DESC: 循环插入1000000 条数据 只需要5s左右 批量插入
     *
     * @author: HX
     * @Time: 2018/9/26   12:00
     *
     */
    public function index2()
    {
        set_time_limit(0);

        $time1 = microtime(true);

        //循环插入一百万
        for ($i=10000; $i <10010000 ; $i+=10000) {
            # code...
            $j = $i-10000;
            $sql = "insert into think_test(name) values ";
            for ($y=$j; $y<$i; $y++) {

                $sql .= "($y),";
            }
            $sql = substr($sql, 0, -1);

            Db::query($sql);
            unset($sql);
        }

        $time2 = microtime(true);

        echo $time2-$time1;
    }

 

转载于:https://my.oschina.net/u/2494575/blog/2221367

发布了162 篇原创文章 · 获赞 31 · 访问量 18万+
展开阅读全文
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览