1/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include "tensorflow/core/lib/core/blocking_counter.h"
17#include "tensorflow/core/lib/core/threadpool.h"
18#include "tensorflow/core/platform/test.h"
19#include "tensorflow/core/platform/test_benchmark.h"
20
21namespace tensorflow {
22namespace {
23
24TEST(BlockingCounterTest, TestZero) {
25  BlockingCounter bc(0);
26  bc.Wait();
27}
28
29TEST(BlockingCounterTest, TestSingleThread) {
30  BlockingCounter bc(2);
31  bc.DecrementCount();
32  bc.DecrementCount();
33  bc.Wait();
34}
35
36TEST(BlockingCounterTest, TestMultipleThread) {
37  int N = 3;
38  thread::ThreadPool* thread_pool =
39      new thread::ThreadPool(Env::Default(), "test", N);
40
41  BlockingCounter bc(N);
42  for (int i = 0; i < N; ++i) {
43    thread_pool->Schedule([&bc] { bc.DecrementCount(); });
44  }
45
46  bc.Wait();
47  delete thread_pool;
48}
49
50}  // namespace
51
52static void BM_BlockingCounter(int iters, int num_threads,
53                               int shards_per_thread) {
54  testing::StopTiming();
55  std::unique_ptr<thread::ThreadPool> thread_pool(
56      new thread::ThreadPool(Env::Default(), "test", num_threads));
57  const int num_shards = num_threads * shards_per_thread;
58  testing::StartTiming();
59  for (int i = 0; i < iters; ++i) {
60    BlockingCounter bc(num_shards);
61    for (int j = 0; j < num_threads; ++j) {
62      thread_pool->Schedule([&bc, shards_per_thread] {
63        for (int k = 0; k < shards_per_thread; ++k) {
64          bc.DecrementCount();
65        }
66      });
67    }
68    bc.Wait();
69  }
70  testing::StopTiming();
71}
72
73BENCHMARK(BM_BlockingCounter)->RangePair(1, 12, 1, 1000);
74
75}  // namespace tensorflow
76