1/* Copyright 2013 Olivier Goffart <ogoffart@woboq.com>
2 http://woboq.com/blog/qmap_qhash_benchmark.html
3*/
4
5#include <QtCore/QtCore>
6#include <unordered_map>
7
8
9#ifndef CONTAINER
10#error CONTAINER must be defined to QMap, QHash, std::map or std::unordered_map
11#endif
12
13namespace std{
14/* std::hash specialization for QString so it can be used
15 * as a key in std::unordered_map */
16template<class Key> struct hash;
17template<> struct hash<QString> {
18 typedef QString Key;
19 typedef uint result_type;
20 inline uint operator()(const QString &s) const { return qHash(s); }
21};
22}
23
24
25int main(int argc, char **argv) {
26 if (argc < 2)
27 qFatal("Missing number of element to add");
28
29 QByteArray a = argv[1];
30 uint num = a.toUInt();
31
32 // creates an array of random keys
33 QVector<QString> strs(num);
34 for (int i=0; i < num; ++i)
35 strs[i] = qvariant_cast<QString>(qrand());
36
37 CONTAINER<QString, QString> c;
38 for (uint i = 0; i < num; ++i) {
39 QString &k = strs[i];
40 c[k] = QString::number(i);
41 }
42
43 quint64 it = 0;
44 const QString *arr = strs.constData();
45
46 QElapsedTimer t;
47 t.start();
48
49 while (t.elapsed() < 1000) {
50 const QString &k = arr[(++it)*797%num];
51 c[k]; // perform a lookup
52 }
53 qDebug() << it/1000;
54}
55