James Kuszmaul | 8e62b02 | 2022-03-22 09:33:25 -0700 | [diff] [blame^] | 1 | #include "benchmarks/cpp/flatbuffers/fb_bench.h" |
| 2 | |
| 3 | #include <cstdint> |
| 4 | #include <memory> |
| 5 | |
| 6 | #include "benchmarks/cpp/bench.h" |
| 7 | #include "benchmarks/cpp/flatbuffers/bench_generated.h" |
| 8 | #include "flatbuffers/flatbuffers.h" |
| 9 | |
| 10 | using namespace flatbuffers; |
| 11 | using namespace benchmarks_flatbuffers; |
| 12 | |
| 13 | namespace { |
| 14 | |
| 15 | struct FlatBufferBench : Bench { |
| 16 | explicit FlatBufferBench(int64_t initial_size, Allocator *allocator) |
| 17 | : fbb(initial_size, allocator, false) {} |
| 18 | |
| 19 | uint8_t *Encode(void *, int64_t &len) { |
| 20 | fbb.Clear(); |
| 21 | |
| 22 | const int kVectorLength = 3; |
| 23 | Offset<FooBar> vec[kVectorLength]; |
| 24 | |
| 25 | for (int i = 0; i < kVectorLength; ++i) { |
| 26 | Foo foo(0xABADCAFEABADCAFE + i, 10000 + i, '@' + i, 1000000 + i); |
| 27 | Bar bar(foo, 123456 + i, 3.14159f + i, 10000 + i); |
| 28 | auto name = fbb.CreateString("Hello, World!"); |
| 29 | auto foobar = |
| 30 | CreateFooBar(fbb, &bar, name, 3.1415432432445543543 + i, '!' + i); |
| 31 | vec[i] = foobar; |
| 32 | } |
| 33 | auto location = fbb.CreateString("http://google.com/flatbuffers/"); |
| 34 | auto foobarvec = fbb.CreateVector(vec, kVectorLength); |
| 35 | auto foobarcontainer = |
| 36 | CreateFooBarContainer(fbb, foobarvec, true, Enum_Bananas, location); |
| 37 | fbb.Finish(foobarcontainer); |
| 38 | |
| 39 | len = fbb.GetSize(); |
| 40 | return fbb.GetBufferPointer(); |
| 41 | } |
| 42 | |
| 43 | int64_t Use(void *decoded) { |
| 44 | sum = 0; |
| 45 | auto foobarcontainer = GetFooBarContainer(decoded); |
| 46 | sum = 0; |
| 47 | Add(foobarcontainer->initialized()); |
| 48 | Add(foobarcontainer->location()->Length()); |
| 49 | Add(foobarcontainer->fruit()); |
| 50 | for (unsigned int i = 0; i < foobarcontainer->list()->Length(); i++) { |
| 51 | auto foobar = foobarcontainer->list()->Get(i); |
| 52 | Add(foobar->name()->Length()); |
| 53 | Add(foobar->postfix()); |
| 54 | Add(static_cast<int64_t>(foobar->rating())); |
| 55 | auto bar = foobar->sibling(); |
| 56 | Add(static_cast<int64_t>(bar->ratio())); |
| 57 | Add(bar->size()); |
| 58 | Add(bar->time()); |
| 59 | auto &foo = bar->parent(); |
| 60 | Add(foo.count()); |
| 61 | Add(foo.id()); |
| 62 | Add(foo.length()); |
| 63 | Add(foo.prefix()); |
| 64 | } |
| 65 | return sum; |
| 66 | } |
| 67 | |
| 68 | void *Decode(void *buffer, int64_t) { return buffer; } |
| 69 | void Dealloc(void *) override{}; |
| 70 | |
| 71 | FlatBufferBuilder fbb; |
| 72 | }; |
| 73 | |
| 74 | } // namespace |
| 75 | |
| 76 | std::unique_ptr<Bench> NewFlatBuffersBench(int64_t initial_size, |
| 77 | Allocator *allocator) { |
| 78 | return std::unique_ptr<FlatBufferBench>( |
| 79 | new FlatBufferBench(initial_size, allocator)); |
| 80 | } |