我寫我的代碼到select在3個線程中併發單線程一個連接;我發現它比1個線程慢;多線程讀取會導致性能下降嗎?
這裏是我的測試數據:
這是一個表(索引uint32)與100000項;
當我在3個一線選擇 10萬項目(所有項目):
0: 1443185531.782627, info: <NSThread: 0x13f99ac40>{number = 4, name = (null)} read ready
1: 1443185531.782634, cost 0.000007, info: <NSThread: 0x13f99ac40>{number = 4, name = (null)} read start
2: 1443185533.365550, cost 1.582916, info: <NSThread: 0x13f99ac40>{number = 4, name = (null)} read end
0: 1443185531.772624, info: <NSThread: 0x13f871e60>{number = 2, name = (null)} read ready
1: 1443185531.782659, cost 0.010035, info: <NSThread: 0x13f871e60>{number = 2, name = (null)} read start
2: 1443185533.372972, cost 1.590313, info: <NSThread: 0x13f871e60>{number = 2, name = (null)} read end
0: 1443185531.773191, info: <NSThread: 0x13f99a6a0>{number = 3, name = (null)} read ready
1: 1443185531.782636, cost 0.009445, info: <NSThread: 0x13f99a6a0>{number = 3, name = (null)} read start
2: 1443185533.393716, cost 1.611080, info: <NSThread: 0x13f99a6a0>{number = 3, name = (null)} read end
你可以看到它的成本1.5秒的平均水平。
但是,當我更改爲選擇 10萬項目(所有項目)在1線:
0: 1443185738.427020, info: <NSThread: 0x14d970990>{number = 2, name = (null)} read ready
1: 1443185738.427106, cost 0.000086, info: <NSThread: 0x14d970990>{number = 2, name = (null)} read start
2: 1443185739.020410, cost 0.593304, info: <NSThread: 0x14d970990>{number = 2, name = (null)} read end
的成本達到0.5秒。
所以我混淆了多線程閱讀會減慢sqlite3的性能。
據我所知,閱讀使用shared-mutex,它可以在多線程中共享。性能下降不應該發生。
有人可以解決我的困惑嗎?
附加:
sqlite3的是在WAL,SQLITE_CONFIG_MULTITHREAD模式,無需任何手動互斥。
附加:
我運行這樣我在3個線程代碼。
//objc code
dispatch_async(name1, ^{
select * in conn1
}
dispatch_async(name2, ^{
select * in conn2
}
dispatch_async(name3, ^{
select * in conn3
}
而不是在每個線程中使用相同的連接(線程不能同時使用),請爲每個線程創建一個連接。 –
我明白每個線程都有自己的句柄sqlite(單線程一個句柄)。您正在以錯誤的方式使用線程。你讓你的軟件做了3次相同的工作,所以它花了更多的時間。 – user430051
@ColonelThirtyTwo我在每個線程中都使用自己的連接。 (寫單線程一連接) –