sqlite插入和查询效率提高方法及测试结果
(2015-10-16 11:52:44)
标签:
股票 |
1、手动开启事务,插入后一次性提交。
2、一次准备(sqlite3_prepare_v2),多次绑定(sqlite3_bind_*)。
3、如果有定期备份的机制,而且少量数据丢失可接受,可将同步方式设置为OFF,默认为FULL。
sqlite3_exec(db, "PRAGMA synchronous = OFF; ", 0,0,0);
4、如果不需要将数据存储到文件,可采用内存模式。
sqlite3_open(":memory:", &db);
5、ournal_mode 调优
sqlite3_exec(db,"pragma journal_mode = WAL; ",0,0,0);
如果在事务执行中程序崩溃或掉电,数据库有可能发生错误。
可参考 http://stackoverflow.com/questions/1711631/improve-insert-per-second-performance-of-sqlite?rq=1
【提高查询效率的方法】
1、创建索引,可以显著提高select的速度,同时也可以提高update的速度。
2、用 replace代替select+insert/update
【测试结果】
|
文件模式, synchronous=FULL |
文件模式, synchronous=OFF |
内存模式, synchronous=FULL |
内存模式, synchronous=OFF |
自动提交模式,调用sqlite3_exec语句 |
11.3s/100条 |
9.4s/100000条 |
12.0s/1000000条 |
12.1s/1000000条 |
自动提交模式,调用sqlite3_prepare_v2和sqlite3_step语句 |
11.7s/100条 |
9.3s/100000条 |
12.0s/1000000条 |
12.0s/1000000条 |
非自动提交模式,调用sqlite3_exec语句 |
10.6s/1000000条 |
10.2s/1000000条 |
9.9s/1000000条 |
10.0s/1000000条 |
非自动提交模式,调用sqlite3_prepare_v2和sqlite3_step语句 |
10.6s/1000000条 |
10.2s/1000000条 |
9.8s/1000000条 |
9.7s/1000000条 |
非自动提交模式,调用sqlite3_prepare_v2和sqlite3_step语句,绑定方式 |
3.5s/1000000条 |
3.2s/1000000条 |
2.9s/1000000条 |
2.9s/1000000条 |
|
无索引 |
有索引 |
|
用select语句在id in (1...10000000)的记录中查找100条记录:id in (1..10) and (1000000...1000010) and (2000000...2000010) and (3000000...3000010) and (4000000...4000010) and (5000000...5000010) and (6000000...6000010) and (7000000...7000010) and (8000000...8000010) and (9000000...9000010) |
9.8s |
0.003s-0.005s |
|
更新或者插入id in (30000001...30000010)的10条记录 |
都需要插入:select + insert |
16.06+1.66=17.72s |
0.002+1.465=1.467s |
都需要更新:select + update |
16.01+17.02=33.03s |
0.002+1.425=1.427s |
|
replace into |
1.4-1.5s |
1.4-1.5s |
【源码】
#include
#include
#include
#include
#include "sqlite3.h"
//#define MAX_NUM 10000000
#define MAX_NUM 10000000
sqlite3 *db;
float timeuse,timeuse1,timeuse2,timeuse3;
struct timeval tstart,tend,t1,t2,t3,t4;
//获得所用时间
void gettimeuse(char *msg, struct timeval start, struct timeval end)
{
}
//打开数据库
void open_database()
{
//
//
}
//创建表
void createTable(sqlite3 *db)
{
//
//
}
//自动提交模式,调用sqlite3_exec语句
void insertdata1()
{
//