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 .....