add TLS access benchmark
[wxWidgets.git] / tests / benchmarks / tls.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: tests/benchmarks/strings.cpp
3 // Purpose: String-related benchmarks
4 // Author: Vadim Zeitlin
5 // Created: 2008-07-19
6 // RCS-ID: $Id$
7 // Copyright: (c) 2008 Vadim Zeitlin <vadim@wxwidgets.org>
8 // Licence: wxWindows license
9 /////////////////////////////////////////////////////////////////////////////
10
11 #include "bench.h"
12
13 #ifdef __UNIX__
14 #define HAVE_PTHREAD
15 #include <pthread.h>
16 #endif
17
18 #if wxCHECK_GCC_VERSION(3, 3)
19 #define HAVE_COMPILER_THREAD
20 #define wxTHREAD_SPECIFIC __thread
21 #endif
22
23 // uncomment this to also test Boost version (you will also need to link with
24 // libboost_threads)
25 //#define HAVE_BOOST_THREAD
26 #ifdef HAVE_BOOST_THREAD
27 #include <boost/thread/tss.hpp>
28 #endif
29
30
31 static const int NUM_ITER = 1000;
32
33 // this is just a baseline
34 BENCHMARK_FUNC(DummyTLS)
35 {
36 static int s_global = 0;
37
38 for ( int n = 0; n < NUM_ITER; n++ )
39 {
40 if ( n % 2 )
41 s_global = 0;
42 else
43 s_global = n;
44 }
45
46 return !s_global;
47 }
48
49 #ifdef HAVE_COMPILER_THREAD
50
51 BENCHMARK_FUNC(CompilerTLS)
52 {
53 static wxTHREAD_SPECIFIC int s_global = 0;
54
55 for ( int n = 0; n < NUM_ITER; n++ )
56 {
57 if ( n % 2 )
58 s_global = 0;
59 else
60 s_global = n;
61 }
62
63 return !s_global;
64 }
65
66 #endif // HAVE_COMPILER_THREAD
67
68 #ifdef HAVE_PTHREAD
69
70 class PthreadKey
71 {
72 public:
73 PthreadKey()
74 {
75 pthread_key_create(&m_key, NULL);
76 }
77
78 ~PthreadKey()
79 {
80 pthread_key_delete(m_key);
81 }
82
83 operator pthread_key_t() const { return m_key; }
84
85 private:
86 pthread_key_t m_key;
87
88 DECLARE_NO_COPY_CLASS(PthreadKey)
89 };
90
91 BENCHMARK_FUNC(PosixTLS)
92 {
93 static PthreadKey s_key;
94
95 for ( int n = 0; n < NUM_ITER; n++ )
96 {
97 if ( n % 2 )
98 pthread_setspecific(s_key, 0);
99 else
100 pthread_setspecific(s_key, &n);
101 }
102
103 return !pthread_getspecific(s_key);
104 }
105
106 #endif // HAVE_PTHREAD
107
108 #ifdef HAVE_BOOST_THREAD
109
110 BENCHMARK_FUNC(BoostTLS)
111 {
112 static boost::thread_specific_ptr<int> s_ptr;
113 if ( !s_ptr.get() )
114 s_ptr.reset(new int(0));
115
116 for ( int n = 0; n < NUM_ITER; n++ )
117 {
118 if ( n % 2 )
119 *s_ptr = 0;
120 else
121 *s_ptr = n;
122 }
123
124 return !*s_ptr;
125 }
126
127 #endif // HAVE_BOOST_THREAD