1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include <benchmark/benchmark.h>
17#include <thread>
18#include "gtest/gtest.h"
19
20#include "ring_buffer.h"
21
22using namespace testing::ext;
23
24namespace Updater {
25
26constexpr uint32_t RING_MAX_LEN = 1024;
27constexpr uint32_t BYTE_SIZE = 255;
28
29class UpdaterBenchmarkTest : public benchmark::Fixture {
30public:
31    UpdaterBenchmarkTest() = default;
32    ~UpdaterBenchmarkTest() override = default;
33    void SetUp(const ::benchmark::State &state) override
34    {}
35    void TearDown(const ::benchmark::State &state) override
36    {}
37};
38
39void ProducerTask(RingBuffer *ringBuffer)
40{
41    for (uint32_t i = 0; i < RING_MAX_LEN; i++) {
42        uint8_t buf[4] {}; // 4: test buffer size
43        buf[0] = i % BYTE_SIZE;
44        buf[1] = i / BYTE_SIZE;
45        ringBuffer->Push(buf, sizeof(buf));
46    }
47}
48
49void ConsumerTask(RingBuffer *ringBuffer)
50{
51    for (uint32_t i = 0; i < RING_MAX_LEN; i++) {
52        uint8_t buf[4] {}; // 4: test buffer size
53        uint32_t len = 0;
54        ringBuffer->Pop(buf, sizeof(buf), len);
55    }
56}
57
58void TestRingBuffer()
59{
60    RingBuffer ringBuffer;
61    bool ret = ringBuffer.Init(1024, 8);
62    EXPECT_TRUE(ret);
63    std::thread consumer(ConsumerTask, &ringBuffer);
64    std::thread producer(ProducerTask, &ringBuffer);
65    consumer.join();
66    producer.join();
67}
68
69BENCHMARK_F(UpdaterBenchmarkTest, TestRingBuffer)(benchmark::State &state)
70{
71    for (auto _ : state) {
72        TestRingBuffer();
73    }
74}
75
76BENCHMARK_REGISTER_F(UpdaterBenchmarkTest, TestRingBuffer)->
77    Iterations(5)->Repetitions(3)->ReportAggregatesOnly();
78
79} // namespace Updater
80
81// Run the benchmark
82BENCHMARK_MAIN();
83