Re: [問題] vector VS array 速度比較

看板C_and_CPP作者 (吃哈吱)時間15年前 (2011/02/01 22:42), 編輯推噓2(205)
留言7則, 4人參與, 最新討論串2/3 (看更多)
※ 引述《linkone (小豆豆)》之銘言: : 現在在看別人的 code 裡面完全都使用 動態陣列來存放東西 : 小弟自己做的話通常會使用 vector 上網爬了一下文 : 好像用動態陣列速度會比較快 又有人說 vector只有在插入時效能才會下降 : 如果是存取的話速度是跟陣列一樣的 想請教一下各位大大的看法 : 不知道陣列跟vector在存取時速度的快與慢如何 小弟之前也有這個疑惑, 就寫了一個簡單的程式來試試 #include <iostream> #include <vector> #include <boost/thread.hpp> int main() { const unsigned int size = 10000000; //array //unsigned int* test = new unsigned int[size]; //vector std::vector<unsigned int> test(size); boost::system_time start_insert = boost::get_system_time(); for( unsigned int i = 0 ; i < size; i++ ) test[i] = i; boost::system_time end_insert = boost::get_system_time(); std::cout << "insert : " << (end_insert-start_insert).total_milliseconds() << " ms" << std::endl; boost::system_time start_access = boost::get_system_time(); for( unsigned int i = 0 ; i < size ; i++ ) { if( test[i] == i ) continue; } boost::system_time end_access = boost::get_system_time(); std::cout << "access : " << (end_access-start_access).total_milliseconds() << " ms" << std::endl; return 0; } 註解那行取消可以改用動態陣列, 目前是用vector. 第一個迴圈是用來計算賦值總時間 第二個迴圈是用來計算存取總時間 用VS2005編譯執行後, 賦值跟存取的結果都是動態陣列速度比vector快上30倍 不知道是否因為程式寫法的問題造成的差異. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.217.23.64

02/01 22:59, , 1F
有開到 release mode嗎?vector 在 debug mode 有加很多料
02/01 22:59, 1F

02/01 23:00, , 2F
我試試
02/01 23:00, 2F

02/01 23:06, , 3F
release mode時, vector插入時間比動態陣列還低幾ms, 但存
02/01 23:06, 3F

02/01 23:06, , 4F
取時間, 動態陣列一直是0ms, vector則是在10~15ms之間
02/01 23:06, 4F

02/01 23:20, , 5F
因為你沒關掉 checked iterators 相關的 bounding check
02/01 23:20, 5F

02/01 23:21, , 6F
這東東 VC Release mode 也是開著的
02/01 23:21, 6F

02/03 19:05, , 7F
樓上說到重點了 這也是那些在哭VC的STL很慢 卻不去要原因
02/03 19:05, 7F
文章代碼(AID): #1DI1lIAy (C_and_CPP)
文章代碼(AID): #1DI1lIAy (C_and_CPP)