自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用C++的StringBuilder提升4350%的性能

開(kāi)發(fā) 后端 開(kāi)發(fā)工具
經(jīng)常出現(xiàn)客戶端打電話抱怨說(shuō):你們的程序慢如蝸牛。你開(kāi)始檢查可能的疑點(diǎn):文件IO,數(shù)據(jù)庫(kù)訪問(wèn)速度,甚至查看web服務(wù)。 但是這些可能的疑點(diǎn)都很正常,一點(diǎn)問(wèn)題都沒(méi)有。

介紹

經(jīng)常出現(xiàn)客戶端打電話抱怨說(shuō):你們的程序慢如蝸牛。你開(kāi)始檢查可能的疑點(diǎn):文件IO,數(shù)據(jù)庫(kù)訪問(wèn)速度,甚至查看web服務(wù)。 但是這些可能的疑點(diǎn)都很正常,一點(diǎn)問(wèn)題都沒(méi)有。

你使用最順手的性能分析工具分析,發(fā)現(xiàn)瓶頸在于一個(gè)小函數(shù),這個(gè)函數(shù)的作用是將一個(gè)長(zhǎng)的字符串鏈表寫(xiě)到一文件中。

你對(duì)這個(gè)函數(shù)做了如下優(yōu)化:將所有的小字符串連接成一個(gè)長(zhǎng)的字符串,執(zhí)行一次文件寫(xiě)入操作,避免成千上萬(wàn)次的小字符串寫(xiě)文件操作。

這個(gè)優(yōu)化只做對(duì)了一半。

你先測(cè)試大字符串寫(xiě)文件的速度,發(fā)現(xiàn)快如閃電。然后你再測(cè)試所有字符串拼接的速度。

好幾年。

怎么回事?你會(huì)怎么克服這個(gè)問(wèn)題呢?

你或許知道.net程序員可以使用StringBuilder來(lái)解決此問(wèn)題。這也是本文的起點(diǎn)。

背景

如果google一下“C++ StringBuilder”,你會(huì)得到不少答案。有些會(huì)建議(你)使用std::accumulate,這可以完成幾乎所有你要實(shí)現(xiàn)的:

  1. #include <iostream>// for std::cout, std::endl  
  2. #include <string>  // for std::string  
  3. #include <vector>  // for std::vector  
  4. #include <numeric> // for std::accumulate  
  5. int main()  
  6. {  
  7.     using namespace std;  
  8.     vector<string> vec = { "hello"" ""world" };  
  9.     string s = accumulate(vec.begin(), vec.end(), s);  
  10.     cout << s << endl; // prints 'hello world' to standard output.   
  11.     return 0;  

目前為止一切都好:當(dāng)你有超過(guò)幾個(gè)字符串連接時(shí),問(wèn)題就出現(xiàn)了,并且內(nèi)存再分配也開(kāi)始積累。

std::string在函數(shù)reserver()中為解決方案提供基礎(chǔ)。這也正是我們的意圖所在:一次分配,隨意連接。

字符串連接可能會(huì)因?yàn)榉敝?、遲鈍的工具而嚴(yán)重影響性能。由于上次存在的隱患,這個(gè)特殊的怪胎給我制造麻煩,我便放棄了Indigo(我想嘗試一些C++11里的令人耳目一新的特性),并寫(xiě)了一個(gè)StringBuilder類(lèi)的部分實(shí)現(xiàn):

  1. // Subset of http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx  
  2. template <typename chr>  
  3. class StringBuilder {  
  4.     typedef std::basic_string<chr> string_t;  
  5.     typedef std::list<string_t> container_t; // Reasons not to use vector below.   
  6.     typedef typename string_t::size_type size_type; // Reuse the size type in the string.  
  7.     container_t m_Data;  
  8.     size_type m_totalSize;  
  9.     void append(const string_t &src) {  
  10.         m_Data.push_back(src);  
  11.         m_totalSize += src.size();  
  12.     }  
  13.     // No copy constructor, no assignement.  
  14.     StringBuilder(const StringBuilder &);  
  15.     StringBuilder & operator = (const StringBuilder &);  
  16. public:  
  17.     StringBuilder(const string_t &src) {  
  18.         if (!src.empty()) {  
  19.             m_Data.push_back(src);  
  20.         }  
  21.         m_totalSize = src.size();  
  22.     }  
  23.     StringBuilder() {  
  24.         m_totalSize = 0;  
  25.     }  
  26.     // TODO: Constructor that takes an array of strings.  
  27.  
  28.  
  29.     StringBuilder & Append(const string_t &src) {  
  30.         append(src);  
  31.         return *this// allow chaining.  
  32.     }  
  33.         // This one lets you add any STL container to the string builder.   
  34.     template<class inputIterator>  
  35.     StringBuilder & Add(const inputIterator &first, const inputIterator &afterLast) {  
  36.         // std::for_each and a lambda look like overkill here.  
  37.                 // <b>Not</b> using std::copy, since we want to update m_totalSize too.  
  38.         for (inputIterator f = first; f != afterLast; ++f) {  
  39.             append(*f);  
  40.         }  
  41.         return *this// allow chaining.  
  42.     }  
  43.     StringBuilder & AppendLine(const string_t &src) {  
  44.         static chr lineFeed[] { 10, 0 }; // C++ 11. Feel the love!  
  45.         m_Data.push_back(src + lineFeed);  
  46.         m_totalSize += 1 + src.size();  
  47.         return *this// allow chaining.  
  48.     }  
  49.     StringBuilder & AppendLine() {  
  50.         static chr lineFeed[] { 10, 0 };   
  51.         m_Data.push_back(lineFeed);  
  52.         ++m_totalSize;  
  53.         return *this// allow chaining.  
  54.     }  
  55.  
  56.     // TODO: AppendFormat implementation. Not relevant for the article.   
  57.  
  58.     // Like C# StringBuilder.ToString()  
  59.     // Note the use of reserve() to avoid reallocations.   
  60.     string_t ToString() const {  
  61.         string_t result;  
  62.         // The whole point of the exercise!  
  63.         // If the container has a lot of strings, reallocation (each time the result grows) will take a serious toll,  
  64.         // both in performance and chances of failure.  
  65.         // I measured (in code I cannot publish) fractions of a second using 'reserve', and almost two minutes using +=.  
  66.         result.reserve(m_totalSize + 1);  
  67.     //  result = std::accumulate(m_Data.begin(), m_Data.end(), result); // This would lose the advantage of 'reserve'  
  68.         for (auto iter = m_Data.begin(); iter != m_Data.end(); ++iter) {   
  69.             result += *iter;  
  70.         }  
  71.         return result;  
  72.     }  
  73.  
  74.     // like javascript Array.join()  
  75.     string_t Join(const string_t &delim) const {  
  76.         if (delim.empty()) {  
  77.             return ToString();  
  78.         }  
  79.         string_t result;  
  80.         if (m_Data.empty()) {  
  81.             return result;  
  82.         }  
  83.         // Hope we don't overflow the size type.  
  84.         size_type st = (delim.size() * (m_Data.size() - 1)) + m_totalSize + 1;  
  85.         result.reserve(st);  
  86.                 // If you need reasons to love C++11, here is one.  
  87.         struct adder {  
  88.             string_t m_Joiner;  
  89.             adder(const string_t &s): m_Joiner(s) {  
  90.                 // This constructor is NOT empty.  
  91.             }  
  92.                         // This functor runs under accumulate() without reallocations, if 'l' has reserved enough memory.   
  93.             string_t operator()(string_t &l, const string_t &r) {  
  94.                 l += m_Joiner;  
  95.                 l += r;  
  96.                 return l;  
  97.             }  
  98.         } adr(delim);  
  99.         auto iter = m_Data.begin();   
  100.                 // Skip the delimiter before the first element in the container.  
  101.         result += *iter;   
  102.         return std::accumulate(++iter, m_Data.end(), result, adr);  
  103.     }  
  104.  
  105. }; // class StringBuilder 

#p#

有趣的部分

函數(shù)ToString()使用std::string::reserve()來(lái)實(shí)現(xiàn)最小化再分配。下面你可以看到一個(gè)性能測(cè)試的結(jié)果。

函數(shù)join()使用std::accumulate(),和一個(gè)已經(jīng)為首個(gè)操作數(shù)預(yù)留內(nèi)存的自定義函數(shù)。

你可能會(huì)問(wèn),為什么StringBuilder::m_Data用std::list而不是std::vector?除非你有一個(gè)用其他容器的好理由,通常都是使用std::vector。

好吧,我(這樣做)有兩個(gè)原因:

1. 字符串總是會(huì)附加到一個(gè)容器的末尾。std::list允許在不需要內(nèi)存再分配的情況下這樣做;因?yàn)関ector是使用一個(gè)連續(xù)的內(nèi)存塊實(shí)現(xiàn)的,每用一個(gè)就可能導(dǎo)致內(nèi)存再分配。

2. std::list對(duì)順序存取相當(dāng)有利,而且在m_Data上所做的唯一存取操作也是順序的。

你可以建議同時(shí)測(cè)試這兩種實(shí)現(xiàn)的性能和內(nèi)存占用情況,然后選擇其中一個(gè)。

性能評(píng)估

為了測(cè)試性能,我從Wikipedia獲取一個(gè)網(wǎng)頁(yè),并將其中一部分內(nèi)容寫(xiě)死到一個(gè)string的vector中。

隨后,我編寫(xiě)兩個(gè)測(cè)試函數(shù),第一個(gè)在兩個(gè)循環(huán)中使用標(biāo)準(zhǔn)函數(shù)clock()并調(diào)用std::accumulate()和StringBuilder::ToString(),然后打印結(jié)果。

  1. void TestPerformance(const StringBuilder<wchar_t> &tested, const std::vector<std::wstring> &tested2) {  
  2.     const int loops = 500;  
  3.     clock_t start = clock(); // Give up some accuracy in exchange for platform independence.  
  4.     for (int i = 0; i < loops; ++i) {  
  5.         std::wstring accumulator;  
  6.         std::accumulate(tested2.begin(), tested2.end(), accumulator);  
  7.     }  
  8.     double secsAccumulate = (double) (clock() - start) / CLOCKS_PER_SEC;  
  9.  
  10.     start = clock();  
  11.     for (int i = 0; i < loops; ++i) {  
  12.         std::wstring result2 = tested.ToString();  
  13.     }  
  14.     double secsBuilder = (double) (clock() - start) / CLOCKS_PER_SEC;  
  15.     using std::cout;  
  16.     using std::endl;  
  17.     cout << "Accumulate took " << secsAccumulate << " seconds, and ToString() took " << secsBuilder << " seconds." 
  18.             << " The relative speed improvement was " << ((secsAccumulate / secsBuilder) - 1) * 100 << "%" 
  19.             << endl;  

第二個(gè)則使用更精確的Posix函數(shù)clock_gettime(),并測(cè)試StringBuilder::Join()。

  1. #ifdef __USE_POSIX199309  
  2.  
  3. // Thanks to <a href="http://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/">Guy Rutenberg</a>.  
  4. timespec diff(timespec start, timespec end)  
  5. {  
  6.     timespec temp;  
  7.     if ((end.tv_nsec-start.tv_nsec)<0) {  
  8.         temp.tv_sec = end.tv_sec-start.tv_sec-1;  
  9.         temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;  
  10.     } else {  
  11.         temp.tv_sec = end.tv_sec-start.tv_sec;  
  12.         temp.tv_nsec = end.tv_nsec-start.tv_nsec;  
  13.     }  
  14.     return temp;  
  15. }  
  16.  
  17. void AccurateTestPerformance(const StringBuilder<wchar_t> &tested, const std::vector<std::wstring> &tested2) {  
  18.     const int loops = 500;  
  19.     timespec time1, time2;  
  20.     // Don't forget to add -lrt to the g++ linker command line.  
  21.     ////////////////  
  22.     // Test std::accumulate()  
  23.     ////////////////  
  24.     clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time1);  
  25.     for (int i = 0; i < loops; ++i) {  
  26.         std::wstring accumulator;  
  27.         std::accumulate(tested2.begin(), tested2.end(), accumulator);  
  28.     }  
  29.     clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time2);  
  30.     using std::cout;  
  31.     using std::endl;  
  32.     timespec tsAccumulate =diff(time1,time2);  
  33.     cout << tsAccumulate.tv_sec << ":" <<  tsAccumulate.tv_nsec << endl;  
  34.     ////////////////  
  35.     // Test ToString()  
  36.     ////////////////  
  37.     clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time1);  
  38.     for (int i = 0; i < loops; ++i) {  
  39.         std::wstring result2 = tested.ToString();  
  40.     }  
  41.     clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time2);  
  42.     timespec tsToString =diff(time1,time2);  
  43.     cout << tsToString.tv_sec << ":" << tsToString.tv_nsec << endl;  
  44.     ////////////////  
  45.     // Test join()  
  46.     ////////////////  
  47.     clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time1);  
  48.     for (int i = 0; i < loops; ++i) {  
  49.         std::wstring result3 = tested.Join(L",");  
  50.     }  
  51.     clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time2);  
  52.     timespec tsJoin =diff(time1,time2);  
  53.     cout << tsJoin.tv_sec << ":" << tsJoin.tv_nsec << endl;  
  54.  
  55.     ////////////////  
  56.     // Show results  
  57.     ////////////////  
  58.     double secsAccumulate = tsAccumulate.tv_sec + tsAccumulate.tv_nsec / 1000000000.0;  
  59.     double secsBuilder = tsToString.tv_sec + tsToString.tv_nsec / 1000000000.0;  
  60.         double secsJoin = tsJoin.tv_sec + tsJoin.tv_nsec / 1000000000.0;  
  61.     cout << "Accurate performance test:" << endl << "    Accumulate took " << secsAccumulate << " seconds, and ToString() took " << secsBuilder << " seconds." << endl  
  62.             << "    The relative speed improvement was " << ((secsAccumulate / secsBuilder) - 1) * 100 << "%" << endl <<  
  63.              "     Join took " << secsJoin << " seconds." 
  64.             << endl;  
  65. }  
  66. #endif // def __USE_POSIX199309 

最后,通過(guò)一個(gè)main函數(shù)調(diào)用以上實(shí)現(xiàn)的兩個(gè)函數(shù),將結(jié)果顯示在控制臺(tái),然后執(zhí)行性能測(cè)試:一個(gè)用于調(diào)試配置。
 

Debug version screenshot

另一個(gè)用于發(fā)行版本:

Release version screenshot

看到這百分比沒(méi)?垃圾郵件的發(fā)送量都不能達(dá)到這個(gè)級(jí)別!
 

#p#

代碼使用

在使用這段代碼前, 考慮使用ostring流。正如你在下面看到Jeff先生評(píng)論的一樣,它比這篇文章中的代碼更快些。

你可能想使用這段代碼,如果:

  • 你正在編寫(xiě)由具有C#經(jīng)驗(yàn)的程序員維護(hù)的代碼,并且你想提供一個(gè)他們所熟悉接口的代碼。
  • 你正在編寫(xiě)將來(lái)會(huì)轉(zhuǎn)換成.net的、你想指出一個(gè)可能路徑的代碼。
  • 由于某些原因,你不想包含<sstream>。幾年之后,一些流的IO實(shí)現(xiàn)變得很繁瑣,而且現(xiàn)在的代碼仍然不能完全擺脫他們的干擾。

要使用這段代碼,只有按照main函數(shù)實(shí)現(xiàn)的那樣就可以了:創(chuàng)建一個(gè)StringBuilder的實(shí)例,用Append()、AppendLine()和Add()給它賦值,然后調(diào)用ToString函數(shù)檢索結(jié)果。

就像下面這樣:

  1. int main() {  
  2.     ////////////////////////////////////  
  3.     // 8-bit characters (ANSI)  
  4.     ////////////////////////////////////  
  5.     StringBuilder<char> ansi;  
  6.     ansi.Append("Hello").Append(" ").AppendLine("World");  
  7.     std::cout << ansi.ToString();  
  8.  
  9.     ////////////////////////////////////  
  10.     // Wide characters (Unicode)  
  11.     ////////////////////////////////////  
  12.     // http://en.wikipedia.org/wiki/Cargo_cult  
  13.     std::vector<std::wstring> cargoCult  
  14.     {  
  15.         L"A", L" cargo", L" cult", L" is", L" a", L" kind", L" of", L" Melanesian", L" millenarian", L" movement",  
  16. // many more lines here...  
  17. L" applied", L" retroactively", L" to", L" movements", L" in", L" a", L" much", L" earlier", L" era.\n" 
  18.     };  
  19.     StringBuilder<wchar_t> wide;  
  20.     wide.Add(cargoCult.begin(), cargoCult.end()).AppendLine();  
  21.         // use ToString(), just like .net  
  22.     std::wcout << wide.ToString() << std::endl;  
  23.     // javascript-like join.  
  24.     std::wcout << wide.Join(L" _\n") << std::endl;  
  25.  
  26.     ////////////////////////////////////  
  27.     // Performance tests  
  28.     ////////////////////////////////////  
  29.     TestPerformance(wide, cargoCult);  
  30. #ifdef __USE_POSIX199309  
  31.     AccurateTestPerformance(wide, cargoCult);  
  32. #endif // def __USE_POSIX199309  
  33.     return 0;  

任何情況下,當(dāng)連接超過(guò)幾個(gè)字符串時(shí),當(dāng)心std::accumulate函數(shù)。

現(xiàn)在稍等一下!

你可能會(huì)問(wèn):你是在試著說(shuō)服我們提前優(yōu)化嗎?

不是的。我贊同提前優(yōu)化是糟糕的。這種優(yōu)化并不是提前的:是及時(shí)的。這是基于經(jīng)驗(yàn)的優(yōu)化:我發(fā)現(xiàn)自己過(guò)去一直在和這種特殊的怪胎搏斗。基于經(jīng)驗(yàn)的優(yōu)化(不在同一個(gè)地方摔倒兩次)并不是提前優(yōu)化。

當(dāng)我們優(yōu)化性能時(shí),“慣犯”會(huì)包括磁盤(pán)I-O操作、網(wǎng)絡(luò)訪問(wèn)(數(shù)據(jù)庫(kù)、web服務(wù))和內(nèi)層循環(huán);對(duì)于這些,我們應(yīng)該添加內(nèi)存分配和性能糟糕的 Keyser Söze

鳴謝

首先,我要為這段代碼在Linux系統(tǒng)上做的精準(zhǔn)分析感謝Rutenberg。

多虧了Wikipedia,讓“在指尖的信息”的夢(mèng)想得以實(shí)現(xiàn)。

最后,感謝你花時(shí)間閱讀這篇文章。希望你喜歡它:不論如何,請(qǐng)分享您的意見(jiàn)。

英文原文:4350% Performance Improvement with the StringBuilder for C++!

譯文鏈接:http://www.oschina.net/translate/performance-improvement-with-the-stringbuilde

責(zé)任編輯:林師授 來(lái)源: OSCHINA編譯
相關(guān)推薦

2017-01-10 14:08:33

C++StringBuild性能

2023-09-26 12:02:34

C++循環(huán)

2024-01-31 23:51:22

C++移動(dòng)語(yǔ)義代碼

2024-04-18 11:07:30

C++語(yǔ)言

2021-06-10 09:40:12

C++性能優(yōu)化Linux

2010-01-26 15:51:06

C++變量

2014-04-17 10:37:43

C++.NET Native

2023-05-12 13:21:12

JMHJava程序

2020-01-21 22:25:00

機(jī)器學(xué)習(xí)人工智能計(jì)算機(jī)

2021-10-14 07:55:17

提示技巧C#

2015-01-06 09:59:03

2023-09-25 13:28:14

C++Lambda

2024-05-16 11:04:06

C#異步編程編程

2022-08-22 15:32:59

C++C代碼

2024-04-07 09:59:42

C++并發(fā)編程開(kāi)發(fā)

2015-11-10 09:25:05

HTTP2提升性能

2015-01-21 15:40:44

GoRuby

2023-12-18 10:11:36

C++17C++代碼

2009-04-14 14:53:06

C++Lambda函數(shù)多線程

2013-05-22 09:38:03

GoGo語(yǔ)言Go性能
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)