MySQL插入10萬數據時間(結論:最快14.967s,每秒插入6681條)


記錄我的一次MySQL操作Demo:


 

存儲過程:


 

DROP PROCEDURE IF EXISTS my_insert;
CREATE PROCEDURE my_insert()
BEGIN
   DECLARE n int DEFAULT 1;
        loopname:LOOP
            INSERT INTO user_info(id,name,age,gender,address,tel)VALUES(n,'lilis',16,2,'杭州下沙',18758);
            SET n=n+1;
        IF n=100000 THEN
            LEAVE loopname;
        END IF;
        END LOOP loopname;
END;
CALL my_insert();

 

表結構:


 


完全插入花費時間:時間: 228.370s(3分多鍾)平均每秒插入:438.6條記錄。


電腦配置信息:內存8g,i3 3217u,固態硬盤(浦科特m6s 128g)。


我覺得這個插入速度太慢了,后來百度的時候注意到MySQL的配置文件中innodb_flush_log_at_trx_commit=2這個配置非常影響寫入性能,默認為1,改成2之后同樣的數據量寫入就快多了,降到了

時間: 14.967s

關於:innodb_flush_log_at_trx_commit這個參數注釋原話是這樣的:

# If set to 1, InnoDB will flush (fsync) the transaction logs to the
# disk at each commit, which offers full ACID behavior. If you are
# willing to compromise this safety, and you are running small
# transactions, you may set this to 0 or 2 to reduce disk I/O to the
# logs. Value 0 means that the log is only written to the log file and
# the log file flushed to disk approximately once per second. Value 2
# means the log is written to the log file at each commit, but the log
# file is only flushed to disk approximately once per second.

翻譯過來就是說設為1時:會在每個事務提交后會執行往磁盤寫日志的操作。設為0或2可減少日志對磁盤IO的負擔。0表示每秒往磁盤寫一次日志,2表示每次事務都往內存提交日志,但每秒往磁盤僅寫入一次。現在想想為什么之前插入這么慢,就是因為每個inset完成后都往磁盤寫日志,導致占滿了磁盤IO(我觀察了磁盤IO,參數設為1的時候磁盤占用時間保持100%)。


 

數據庫庫優化有4層次:

1.sql語句及索引優化(性價比最高,最容易操作)

2.表結構優化(數據庫設計層面)

3.數據庫配置優化

4.硬件的升級

我遇到的這個問題就屬於第3個層次。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM