aboutsummaryrefslogtreecommitdiff
path: root/common/kvstore/src/test/java/org/apache/spark/kvstore/LevelDBBenchmark.java
blob: 5e33606b12dd41a807014c006063287d5cf5eac5 (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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.spark.kvstore;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.Timer;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;

/**
 * A set of small benchmarks for the LevelDB implementation.
 *
 * The benchmarks are run over two different types (one with just a natural index, and one
 * with a ref index), over a set of 2^20 elements, and the following tests are performed:
 *
 * - write (then update) elements in sequential natural key order
 * - write (then update) elements in random natural key order
 * - iterate over natural index, ascending and descending
 * - iterate over ref index, ascending and descending
 */
@Ignore
public class LevelDBBenchmark {

  private static final int COUNT = 1024;
  private static final AtomicInteger IDGEN = new AtomicInteger();
  private static final MetricRegistry metrics = new MetricRegistry();
  private static final Timer dbCreation = metrics.timer("dbCreation");
  private static final Timer dbClose = metrics.timer("dbClose");

  private LevelDB db;
  private File dbpath;

  @Before
  public void setup() throws Exception {
    dbpath = File.createTempFile("test.", ".ldb");
    dbpath.delete();
    try(Timer.Context ctx = dbCreation.time()) {
      db = new LevelDB(dbpath);
    }
  }

  @After
  public void cleanup() throws Exception {
    if (db != null) {
      try(Timer.Context ctx = dbClose.time()) {
        db.close();
      }
    }
    if (dbpath != null) {
      FileUtils.deleteQuietly(dbpath);
    }
  }

  @AfterClass
  public static void report() {
    if (metrics.getTimers().isEmpty()) {
      return;
    }

    int headingPrefix = 0;
    for (Map.Entry<String, Timer> e : metrics.getTimers().entrySet()) {
      headingPrefix = Math.max(e.getKey().length(), headingPrefix);
    }
    headingPrefix += 4;

    StringBuilder heading = new StringBuilder();
    for (int i = 0; i < headingPrefix; i++) {
      heading.append(" ");
    }
    heading.append("\tcount");
    heading.append("\tmean");
    heading.append("\tmin");
    heading.append("\tmax");
    heading.append("\t95th");
    System.out.println(heading);

    for (Map.Entry<String, Timer> e : metrics.getTimers().entrySet()) {
      StringBuilder row = new StringBuilder();
      row.append(e.getKey());
      for (int i = 0; i < headingPrefix - e.getKey().length(); i++) {
        row.append(" ");
      }

      Snapshot s = e.getValue().getSnapshot();
      row.append("\t").append(e.getValue().getCount());
      row.append("\t").append(toMs(s.getMean()));
      row.append("\t").append(toMs(s.getMin()));
      row.append("\t").append(toMs(s.getMax()));
      row.append("\t").append(toMs(s.get95thPercentile()));

      System.out.println(row);
    }

    Slf4jReporter.forRegistry(metrics).outputTo(LoggerFactory.getLogger(LevelDBBenchmark.class))
      .build().report();
  }

  private static String toMs(double nanos) {
    return String.format("%.3f", nanos / 1000 / 1000);
  }

  @Test
  public void sequentialWritesNoIndex() throws Exception {
    List<SimpleType> entries = createSimpleType();
    writeAll(entries, "sequentialWritesNoIndex");
    writeAll(entries, "sequentialUpdatesNoIndex");
    deleteNoIndex(entries, "sequentialDeleteNoIndex");
  }

  @Test
  public void randomWritesNoIndex() throws Exception {
    List<SimpleType> entries = createSimpleType();

    Collections.shuffle(entries);
    writeAll(entries, "randomWritesNoIndex");

    Collections.shuffle(entries);
    writeAll(entries, "randomUpdatesNoIndex");

    Collections.shuffle(entries);
    deleteNoIndex(entries, "randomDeletesNoIndex");
  }

  @Test
  public void sequentialWritesIndexedType() throws Exception {
    List<IndexedType> entries = createIndexedType();
    writeAll(entries, "sequentialWritesIndexed");
    writeAll(entries, "sequentialUpdatesIndexed");
    deleteIndexed(entries, "sequentialDeleteIndexed");
  }

  @Test
  public void randomWritesIndexedTypeAndIteration() throws Exception {
    List<IndexedType> entries = createIndexedType();

    Collections.shuffle(entries);
    writeAll(entries, "randomWritesIndexed");

    Collections.shuffle(entries);
    writeAll(entries, "randomUpdatesIndexed");

    // Run iteration benchmarks here since we've gone through the trouble of writing all
    // the data already.
    KVStoreView<?> view = db.view(IndexedType.class);
    iterate(view, "naturalIndex");
    iterate(view.reverse(), "naturalIndexDescending");
    iterate(view.index("name"), "refIndex");
    iterate(view.index("name").reverse(), "refIndexDescending");

    Collections.shuffle(entries);
    deleteIndexed(entries, "randomDeleteIndexed");
  }

  private void iterate(KVStoreView<?> view, String name) throws Exception {
    Timer create = metrics.timer(name + "CreateIterator");
    Timer iter = metrics.timer(name + "Iteration");
    KVStoreIterator<?> it = null;
    {
      // Create the iterator several times, just to have multiple data points.
      for (int i = 0; i < 1024; i++) {
        if (it != null) {
          it.close();
        }
        try(Timer.Context ctx = create.time()) {
          it = view.closeableIterator();
        }
      }
    }

    for (; it.hasNext(); ) {
      try(Timer.Context ctx = iter.time()) {
        it.next();
      }
    }
  }

  private void writeAll(List<?> entries, String timerName) throws Exception {
    Timer timer = newTimer(timerName);
    for (Object o : entries) {
      try(Timer.Context ctx = timer.time()) {
        db.write(o);
      }
    }
  }

  private void deleteNoIndex(List<SimpleType> entries, String timerName) throws Exception {
    Timer delete = newTimer(timerName);
    for (SimpleType i : entries) {
      try(Timer.Context ctx = delete.time()) {
        db.delete(i.getClass(), i.key);
      }
    }
  }

  private void deleteIndexed(List<IndexedType> entries, String timerName) throws Exception {
    Timer delete = newTimer(timerName);
    for (IndexedType i : entries) {
      try(Timer.Context ctx = delete.time()) {
        db.delete(i.getClass(), i.key);
      }
    }
  }

  private List<SimpleType> createSimpleType() {
    List<SimpleType> entries = new ArrayList<>();
    for (int i = 0; i < COUNT; i++) {
      SimpleType t = new SimpleType();
      t.key = IDGEN.getAndIncrement();
      t.name = "name" + (t.key % 1024);
      entries.add(t);
    }
    return entries;
  }

  private List<IndexedType> createIndexedType() {
    List<IndexedType> entries = new ArrayList<>();
    for (int i = 0; i < COUNT; i++) {
      IndexedType t = new IndexedType();
      t.key = IDGEN.getAndIncrement();
      t.name = "name" + (t.key % 1024);
      entries.add(t);
    }
    return entries;
  }

  private Timer newTimer(String name) {
    assertNull("Timer already exists: " + name, metrics.getTimers().get(name));
    return metrics.timer(name);
  }

  public static class SimpleType {

    @KVIndex
    public int key;

    public String name;

  }

  public static class IndexedType {

    @KVIndex
    public int key;

    @KVIndex("name")
    public String name;

  }

}