1/**
2 * Copyright (c) Glow Contributors. See CONTRIBUTORS file.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef GLOW_TESTS_BENCHMARK_H
17#define GLOW_TESTS_BENCHMARK_H
18
19#include <algorithm>
20#include <chrono>
21#include <limits>
22#include <tuple>
23#include <vector>
24
25#include "glow/Base/DimType.h"
26#include "llvm/Support/CommandLine.h"
27
28namespace glow {
29
30/// Interface for benchmarks
31class Benchmark {
32public:
33 virtual ~Benchmark() = default;
34 virtual void setup() = 0;
35 virtual void run() = 0;
36 virtual void teardown() = 0;
37};
38
39/// Run a benchmark \p reps times and return the execution times
40std::vector<double> bench(Benchmark *b, size_t reps) {
41 std::vector<double> times(reps);
42 b->setup();
43 for (size_t i = 0; i < reps; i++) {
44 auto start = std::chrono::high_resolution_clock::now();
45 b->run();
46 auto end = std::chrono::high_resolution_clock::now();
47 auto duration = std::chrono::duration<double>(end - start).count();
48 times[i] = duration;
49 }
50 b->teardown();
51 return times;
52}
53
54std::vector<dim_t> getBatchSizePerCore(size_t batchSize, dim_t numCores) {
55 std::vector<dim_t> batchSizePerCore(numCores);
56 for (dim_t core = 0; core < numCores; core++) {
57 dim_t perCore = (batchSize + numCores - 1) / numCores;
58 dim_t startIdx = core * perCore;
59 dim_t endIdx = (core + 1) * perCore;
60 if (startIdx > batchSize)
61 startIdx = batchSize;
62 if (endIdx > batchSize)
63 endIdx = batchSize;
64 batchSizePerCore[core] = (endIdx - startIdx);
65 }
66 return batchSizePerCore;
67}
68
69inline void benchParseGlowOpts(int argc, const char *const *argv,
70 const char *envvar = "GLOW_OPTS") {
71#if LLVM_VERSION_MAJOR < 8
72 llvm::cl::ParseEnvironmentOptions(argv[0], envvar);
73#else
74 llvm::cl::ParseCommandLineOptions(1, argv, "", nullptr, envvar);
75#endif
76}
77
78} // namespace glow
79
80#endif // GLOW_TESTS_BENCHMARK_H
81