如何加快sqlite数据库的加载速度? (sqlite3_step非常慢)

时间:2016-11-24 18:21:50

标签: c++ performance sqlite

我可能有大约1,000,000行加载到C ++对象中(通过大约10,000个SELECTS)。我已经分析了负载,并注意到这里的sqlite3_step语句是瓶颈。

sqlite3_stmt *stmt;
std::string symbol = stock->getSymbol();
boost::format sql("SELECT date,open,high,low,close,volume FROM Prices WHERE symbol=\"%s\" ORDER BY date DESC");
sql % symbol;

if (sqlite3_prepare_v2(databaseHandle_, sql.str().c_str(), -1, &stmt, NULL) == SQLITE_OK) {
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        int date = sqlite3_column_int(stmt, 0);
        float open = sqlite3_column_double(stmt, 1);
        float high = sqlite3_column_double(stmt, 2);
        float low = sqlite3_column_double(stmt, 3);
        float close = sqlite3_column_double(stmt, 4);
        int volume = sqlite3_column_int(stmt, 5);
        Price *price = new Price(new Date(date), open, close, low, high, volume);
        stock->add(price);
    }
} else {
    std::cout << "Error loading stock" << std::endl;
}

我正在使用amagalmated sqlite.h / c 3.15.0版。有什么想法可以加快表现吗?

更多信息:

CREATE TABLE Prices (symbol VARCHAR(10) NOT NULL, date INT(11) NOT NULL, open DECIMAL(6,2) NOT NULL, high DECIMAL(6,2) NOT NULL,low DECIMAL(6,2) NOT NULL, close DECIMAL(6,2) NOT NULL, volume INT(10) NOT NULL, PRIMARY KEY (symbol, date))

CREATE INDEX `PricesIndex` ON `Prices` (`symbol` ,`date` DESC)

EXPLAIN QUERY PLAN SELECT * FROM Prices WHERE symbol="TSLA" ORDER BY date DESC;

返回

SEARCH TABLE PRICES USING INDEX PricesIndex (symbol=?)

进一步说明:如上所示的这样的SELECT在SQLite浏览器中用于Mac执行SQL需要2ms。

1 个答案:

答案 0 :(得分:0)

您的索引已经加快搜索匹配的行,并以正确的顺序返回它们,因此不需要单独的排序步骤。

但是,数据库仍然需要为每个索引条目查找相应的表行。 您可以通过在所有已使用的列上创建covering index来加快此特定查询的速度:

CREATE INDEX p ON Prices(symbol, date, open, high, low, close, volume);

但是,不要复制索引中的所有数据,最好将此表格设为clustered index

CREATE TABLE Prices (
    symbol VARCHAR(10) NOT NULL,
    date INT(11) NOT NULL,
    open DECIMAL(6,2) NOT NULL,
    high DECIMAL(6,2) NOT NULL,
    low DECIMAL(6,2) NOT NULL,
    close DECIMAL(6,2) NOT NULL,
    volume INT(10) NOT NULL,
    PRIMARY KEY (symbol, date)
) WITHOUT ROWID;
相关问题