[C ++ 11] shared_ptr Efficiency Comparison

Source: Internet
Author: User

Shared_ptr in C ++ 11 is used in the network library I implemented. I made profile yesterday and found that many CPUs are consumed on shared_ptr. So I plan to see how efficient shared_ptr is.

The experiment is like this. Get a temporary shared_ptr and copy times continuously to see how long it takes. the subjects are GCC 4.6.2 and clang 3.1 (libc ++ ). finally, output the time consumed, compilation options, O0 and O2.

UpperCode:

# Include <thread> # Include <Memory> # Include <Unistd. h> # Include <Iostream> # Include <Sys/time. h> Long  Getmillionsecond () {timeval val;: gettimeofday ( & Val, null );  Return Val. TV _sec * 1000 + Val. TV _usec/ 1000  ;}  Int  Main () {# ifdef thread  Int Terminal = False  ; STD: thread t ([ & ] {  While (! Terminal): usleep (  1000 * 1000  );}); # Endif    Long Begin_time = Getmillionsecond (); STD: shared_ptr < Int > P ( New   Int  );  For ( Int I = 0 ; I < 100 * 10000 ; ++ I) {STD: shared_ptr < Int > A = P; * A = I ;}  Long End_time = Getmillionsecond (); # ifdef thread Terminal = True  ; T. Join ();  # Endif  STD: cout <* P < STD: Endl; STD: cout <End_time-begin_time < "  MS  " < STD: Endl; Return   0  ;} 

Test results:

Compiler/Optimization Options -O0 (unit: MS) -O2 (unit: MS)
Clang 44 ~ 49 37 ~ 39
Clang thread 40 ~ 49 31 ~ 39
Gcc 85 ~ 92 26 ~ 31
GCC thread 87 ~ 92 28 ~ 33

It is not clear whether single-thread optimization is implemented in libstdc ++ of GCC 4.6.2, and it must be optimized in 4.7. Try again on GCC 4.7 tomorrow.

As you can see, enabling the optimization option has an impact on both implementations. The GCC optimization capability is strong.

Shared_ptr is very efficient. I only tested the server at the time and didn't enable the optimization option. So if I copied messages two or three times, it was a little tight.

PS:

The optimization of GCC 4.7 seems to be no different from that of 4.6 .....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.