blob: 22b83d0ea32965517434688dc2284218796e641c (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
/**
* Benchmark of different locking mechanisms; QMutex, PosixMutex, Silly
* (int-flag).
*/
#include <QtCore>
#include <QtNetwork>
#include "Timer.h"
// It's important this is high enough the process doesn't complete in
// one timeslice.
#define ITER 100000000
typedef QPair<quint64,int> tr;
class SillyLock {
public:
int counter;
SillyLock();
void lock();
void unlock();
};
SillyLock::SillyLock() {
counter = 0;
}
void SillyLock::lock() {
if (counter == 0)
counter = 1;
else
qFatal("Recursive lock");
}
void SillyLock::unlock() {
if (counter == 1)
counter = 0;
else
qFatal("Nonlock-unlock");
}
class PosixLock {
public:
pthread_mutex_t m;
PosixLock();
void lock();
void unlock();
};
PosixLock::PosixLock() {
pthread_mutex_init(&m, nullptr);
}
void PosixLock::lock() {
pthread_mutex_lock(&m);
}
void PosixLock::unlock() {
pthread_mutex_unlock(&m);
}
template<class T>
class SpeedTest {
public:
T &lock;
SpeedTest(T &l) : lock(l) {
}
quint64 test() {
Timer t;
t.restart();
for (int i=0;i<ITER;i++) {
lock.lock();
lock.unlock();
}
return t.elapsed();
}
};
int main(int argc, char **argv) {
QCoreApplication a(argc, argv);
QMutex qm;
QMutex qmr(QMutex::Recursive);
SillyLock sl;
PosixLock pl;
SpeedTest<QMutex> stqm(qm);
SpeedTest<QMutex> stqmr(qmr);
SpeedTest<SillyLock> stsl(sl);
SpeedTest<PosixLock> stpl(pl);
quint64 elapsed;
elapsed = stsl.test();
qWarning("SillyLock: %8lld", elapsed);
elapsed = stqm.test();
qWarning("QMutex : %8lld", elapsed);
elapsed = stqmr.test();
qWarning("QMutexR : %8lld", elapsed);
elapsed = stpl.test();
qWarning("PosixLock: %8lld", elapsed);
}
// #include "Lock.moc"
|