forked from googleapis/google-cloud-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultiple_rows_cpu_benchmark.cc
More file actions
1437 lines (1304 loc) · 53.6 KB
/
multiple_rows_cpu_benchmark.cc
File metadata and controls
1437 lines (1304 loc) · 53.6 KB
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 Google LLC
//
// Licensed 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
//
// https://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.
#include "google/cloud/internal/disable_deprecation_warnings.inc"
#include "google/cloud/spanner/admin/database_admin_client.h"
#include "google/cloud/spanner/benchmarks/benchmarks_config.h"
#include "google/cloud/spanner/client.h"
#include "google/cloud/spanner/internal/defaults.h"
#include "google/cloud/spanner/internal/route_to_leader.h"
#include "google/cloud/spanner/internal/session_pool.h"
#include "google/cloud/spanner/internal/spanner_stub_factory.h"
#include "google/cloud/spanner/testing/pick_random_instance.h"
#include "google/cloud/spanner/testing/random_database_name.h"
#include "google/cloud/grpc_error_delegate.h"
#include "google/cloud/grpc_options.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/random.h"
#include "google/cloud/internal/unified_grpc_credentials.h"
#include "google/cloud/testing_util/timer.h"
#include "absl/strings/str_cat.h"
#include "absl/time/civil_time.h"
#include "google/spanner/v1/result_set.pb.h"
#include <grpcpp/grpcpp.h>
#include <algorithm>
#include <chrono>
#include <future>
#include <limits>
#include <numeric>
#include <random>
#include <sstream>
#include <thread>
/**
* @file
*
* A CPU cost per call benchmark for the Cloud Spanner C++ client library.
*
* This program measures the CPU cost of multiple single-row operations in the
* client library. Other techniques, such as using the time(1) program, can
* yield inaccurate results as the setup costs (creating a table, populating it
* with some initial data) can be very high.
*/
namespace {
namespace spanner = ::google::cloud::spanner;
namespace spanner_internal = ::google::cloud::spanner_internal;
using ::google::cloud::Status;
using ::google::cloud::spanner_benchmarks::Config;
using ::google::cloud::testing_util::Timer;
struct RowCpuSample {
int channel_count;
int thread_count;
bool using_stub;
int row_count;
std::chrono::microseconds elapsed;
std::chrono::microseconds cpu_time;
Status status;
};
std::ostream& operator<<(std::ostream& os, RowCpuSample const& s) {
return os << s.channel_count << ',' << s.thread_count << ',' << s.using_stub
<< ',' << s.row_count << ',' << s.elapsed.count() << ','
<< s.cpu_time.count() << ',' << s.status.code();
}
bool SupportPerThreadUsage() {
#if GOOGLE_CLOUD_CPP_HAVE_RUSAGE_THREAD
return true;
#else
return false;
#endif // GOOGLE_CLOUD_CPP_HAVE_RUSAGE_THREAD
}
struct BoolTraits {
using native_type = bool;
static std::string SpannerDataType() { return "BOOL"; }
static std::string TableSuffix() { return "bool"; }
static native_type MakeRandomValue(
google::cloud::internal::DefaultPRNG& generator) {
return std::uniform_int_distribution<int>(0, 1)(generator) == 1;
}
};
struct BytesTraits {
using native_type = spanner::Bytes;
static std::string SpannerDataType() { return "BYTES(1024)"; }
static std::string TableSuffix() { return "bytes"; }
static native_type MakeRandomValue(
google::cloud::internal::DefaultPRNG& generator) {
static auto const* const kPopulation = new auto([] {
std::string result;
// NOLINTNEXTLINE(bugprone-signed-char-misuse)
int constexpr kCharMin = (std::numeric_limits<char>::min)();
int constexpr kCharMax = (std::numeric_limits<char>::max)();
for (auto c = kCharMin; c <= kCharMax; ++c) {
result.push_back(static_cast<char>(c));
}
return result;
}());
std::string tmp =
google::cloud::internal::Sample(generator, 1024, *kPopulation);
return spanner::Bytes(tmp.begin(), tmp.end());
}
};
struct DateTraits {
using native_type = absl::CivilDay;
static std::string SpannerDataType() { return "DATE"; }
static std::string TableSuffix() { return "date"; }
static native_type MakeRandomValue(
google::cloud::internal::DefaultPRNG& generator) {
return native_type{
std::uniform_int_distribution<std::int64_t>(1, 2000)(generator),
std::uniform_int_distribution<int>(1, 12)(generator),
std::uniform_int_distribution<int>(1, 28)(generator)};
}
};
struct Float64Traits {
using native_type = double;
static std::string SpannerDataType() { return "FLOAT64"; }
static std::string TableSuffix() { return "float64"; }
static native_type MakeRandomValue(
google::cloud::internal::DefaultPRNG& generator) {
return std::uniform_real_distribution<double>(0.0, 1.0)(generator);
}
};
struct Int64Traits {
using native_type = std::int64_t;
static std::string SpannerDataType() { return "INT64"; }
static std::string TableSuffix() { return "int64"; }
static native_type MakeRandomValue(
google::cloud::internal::DefaultPRNG& generator) {
return std::uniform_int_distribution<std::int64_t>(
std::numeric_limits<std::int64_t>::min(),
std::numeric_limits<std::int64_t>::max())(generator);
}
};
struct StringTraits {
using native_type = std::string;
static std::string SpannerDataType() { return "STRING(1024)"; }
static std::string TableSuffix() { return "string"; }
static native_type MakeRandomValue(
google::cloud::internal::DefaultPRNG& generator) {
return google::cloud::internal::Sample(
generator, 1024, "#@$%^&*()-=+_0123456789[]{}|;:,./<>?");
}
};
struct TimestampTraits {
using native_type = spanner::Timestamp;
static std::string SpannerDataType() { return "TIMESTAMP"; }
static std::string TableSuffix() { return "timestamp"; }
static native_type MakeRandomValue(
google::cloud::internal::DefaultPRNG& generator) {
auto const tp =
std::chrono::system_clock::time_point{} +
std::chrono::nanoseconds(
std::uniform_int_distribution<std::chrono::nanoseconds::rep>(
0, std::numeric_limits<std::chrono::nanoseconds::rep>::max())(
generator));
return spanner::MakeTimestamp(tp).value();
}
};
struct NumericTraits {
using native_type = spanner::Numeric;
static std::string SpannerDataType() { return "NUMERIC"; }
static std::string TableSuffix() { return "numeric"; }
static native_type MakeRandomValue(
google::cloud::internal::DefaultPRNG& generator) {
return spanner::MakeNumeric(
std::uniform_int_distribution<std::int64_t>(
std::numeric_limits<std::int64_t>::min(),
std::numeric_limits<std::int64_t>::max())(generator),
-9) // scale by 10^-9
.value();
}
};
template <typename Traits>
class ExperimentImpl {
public:
explicit ExperimentImpl(google::cloud::internal::DefaultPRNG const& generator)
: generator_(generator) {}
static int constexpr kColumnCount = 10;
std::string CreateTableStatement(std::string const& table_name) {
std::string statement = "CREATE TABLE " + table_name;
statement += " (Key INT64 NOT NULL,\n";
for (int i = 0; i != kColumnCount; ++i) {
statement +=
"Data" + std::to_string(i) + " " + Traits::SpannerDataType() + ",\n";
}
statement += ") PRIMARY KEY (Key)";
return statement;
}
Status FillTable(Config const& config, spanner::Database const& database,
std::string const& table_name) {
// We need to populate some data or all the requests to read will fail.
spanner::Client client(spanner::MakeConnection(database));
std::cout << "# Populating database " << std::flush;
int const task_count = 16;
std::vector<std::future<void>> tasks(task_count);
int task_id = 0;
for (auto& t : tasks) {
t = std::async(
std::launch::async,
[this, &config, &client, &table_name](int tc, int ti) {
FillTableTask(config, client, table_name, tc, ti);
},
task_count, task_id++);
}
for (auto& t : tasks) {
t.get();
}
std::cout << " DONE\n";
return {};
}
typename Traits::native_type GenerateRandomValue() {
std::lock_guard<std::mutex> lk(mu_);
return Traits::MakeRandomValue(generator_);
}
std::int64_t RandomKey(Config const& config) {
std::lock_guard<std::mutex> lk(mu_);
return std::uniform_int_distribution<std::int64_t>(
0, config.table_size - 1)(generator_);
}
std::int64_t RandomKeySetBegin(Config const& config) {
std::lock_guard<std::mutex> lk(mu_);
return std::uniform_int_distribution<std::int64_t>(
0, config.table_size - config.query_size)(generator_);
}
spanner::KeySet RandomKeySet(Config const& config) {
auto begin = RandomKeySetBegin(config);
auto end = begin + config.query_size - 1;
return spanner::KeySet().AddRange(
spanner::MakeKeyBoundClosed(spanner::Value(begin)),
spanner::MakeKeyBoundClosed(spanner::Value(end)));
}
bool UseStub(Config const& config) {
if (config.use_only_clients) {
return false;
}
if (config.use_only_stubs) {
return true;
}
std::lock_guard<std::mutex> lk(mu_);
return std::uniform_int_distribution<int>(0, 1)(generator_) == 1;
}
int ThreadCount(Config const& config) {
std::lock_guard<std::mutex> lk(mu_);
return std::uniform_int_distribution<int>(
config.minimum_threads, config.maximum_threads)(generator_);
}
int ChannelCount(Config const& config) {
std::lock_guard<std::mutex> lk(mu_);
return std::uniform_int_distribution<int>(
config.minimum_channels, config.maximum_channels)(generator_);
}
spanner::Client MakeClient(Config const& config,
spanner::Database const& database) {
auto num_channels = config.maximum_channels;
std::cout << "# Creating 1 client using shared connection with "
<< num_channels << " channel" << (num_channels != 1 ? "s" : "")
<< "\n"
<< std::flush;
auto connection = spanner::MakeConnection(
database,
// This pre-creates all the Sessions we will need (one per thread).
google::cloud::Options{}
.set<google::cloud::GrpcNumChannelsOption>(num_channels)
.set<spanner::SessionPoolMinSessionsOption>(
config.maximum_threads));
return spanner::Client(std::move(connection));
}
std::vector<std::shared_ptr<spanner_internal::SpannerStub>> MakeStubs(
Config const& config, spanner::Database const& db) {
auto num_channels = config.maximum_channels;
std::cout << "# Creating " << num_channels << " stub"
<< (num_channels != 1 ? "s" : "") << "\n"
<< std::flush;
auto opts =
google::cloud::Options{}.set<google::cloud::GrpcNumChannelsOption>(
num_channels);
opts = spanner_internal::DefaultOptions(std::move(opts));
auto auth = google::cloud::internal::CreateAuthenticationStrategy(
opts.get<google::cloud::GrpcCredentialOption>());
std::vector<std::shared_ptr<spanner_internal::SpannerStub>> stubs;
stubs.reserve(num_channels);
for (int channel_id = 0; channel_id < num_channels; ++channel_id) {
stubs.push_back(spanner_internal::CreateDefaultSpannerStub(db, auth, opts,
channel_id));
}
return stubs;
}
void DumpSamples(std::vector<RowCpuSample> const& samples) const {
std::lock_guard<std::mutex> lk(mu_);
std::copy(samples.begin(), samples.end(),
std::ostream_iterator<RowCpuSample>(std::cout, "\n"));
auto it =
std::find_if(samples.begin(), samples.end(),
[](RowCpuSample const& x) { return !x.status.ok(); });
if (it == samples.end()) {
return;
}
std::cout << "# FIRST ERROR: " << it->status << "\n";
}
void LogError(std::string const& s) {
std::lock_guard<std::mutex> lk(mu_);
std::cout << "# " << s << std::endl;
}
private:
Status FillTableTask(Config const& config, spanner::Client client,
std::string const& table_name, int task_count,
int task_id) {
std::vector<std::string> const column_names{
"Key", "Data0", "Data1", "Data2", "Data3", "Data4",
"Data5", "Data6", "Data7", "Data8", "Data9"};
using T = typename Traits::native_type;
T value0 = GenerateRandomValue();
T value1 = GenerateRandomValue();
T value2 = GenerateRandomValue();
T value3 = GenerateRandomValue();
T value4 = GenerateRandomValue();
T value5 = GenerateRandomValue();
T value6 = GenerateRandomValue();
T value7 = GenerateRandomValue();
T value8 = GenerateRandomValue();
T value9 = GenerateRandomValue();
auto mutation =
spanner::InsertOrUpdateMutationBuilder(table_name, column_names);
int current_mutations = 0;
auto maybe_flush = [&](bool force) -> Status {
if (current_mutations == 0) {
return {};
}
if (!force && current_mutations < 1000) {
return {};
}
auto result =
client.Commit(spanner::Mutations{std::move(mutation).Build()});
if (!result) {
std::lock_guard<std::mutex> lk(mu_);
std::cout << "# Error in Commit() " << result.status() << "\n";
return std::move(result).status();
}
mutation =
spanner::InsertOrUpdateMutationBuilder(table_name, column_names);
current_mutations = 0;
return {};
};
auto force_flush = [&maybe_flush] { return maybe_flush(true); };
auto flush_as_needed = [&maybe_flush] { return maybe_flush(false); };
auto const report_period =
(std::max)(static_cast<std::int32_t>(2), config.table_size / 50);
for (std::int64_t key = 0; key != config.table_size; ++key) {
// Each thread does a fraction of the key space.
if (key % task_count != task_id) continue;
// Have one of the threads report progress about 50 times.
if (task_id == 0 && key % report_period == 0) {
std::lock_guard<std::mutex> lk(mu_);
std::cout << '.' << std::flush;
}
mutation.EmplaceRow(key, value0, value1, value2, value3, value4, value5,
value6, value7, value8, value9);
++current_mutations;
auto status = flush_as_needed();
if (!status.ok()) return status;
}
return force_flush();
}
mutable std::mutex mu_;
google::cloud::internal::DefaultPRNG generator_;
};
class Experiment {
public:
virtual ~Experiment() = default;
virtual std::string AdditionalDdlStatement() = 0;
virtual Status SetUp(Config const& config,
spanner::Database const& database) = 0;
virtual Status Run(Config const& config,
spanner::Database const& database) = 0;
};
template <typename Traits>
class BasicExperiment : public Experiment {
public:
explicit BasicExperiment(google::cloud::internal::DefaultPRNG generator,
std::string table_prefix)
: impl_(generator),
table_name_(absl::StrCat(std::move(table_prefix), "Experiment_",
Traits::TableSuffix())) {}
std::string AdditionalDdlStatement() override {
return impl_.CreateTableStatement(table_name_);
}
Status SetUp(Config const& config,
spanner::Database const& database) override {
return impl_.FillTable(config, database, table_name_);
}
Status Run(Config const& config, spanner::Database const& database) override {
auto client = impl_.MakeClient(config, database);
auto stubs = impl_.MakeStubs(config, database);
// Capture some overall getrusage() statistics as comments.
auto overall = Timer::PerProcess();
for (int i = 0; i != config.samples; ++i) {
auto const use_stubs = impl_.UseStub(config);
auto const thread_count = impl_.ThreadCount(config);
auto const channel_count = impl_.ChannelCount(config);
if (use_stubs) {
std::vector<std::shared_ptr<spanner_internal::SpannerStub>>
iteration_stubs(stubs.begin(), stubs.begin() + channel_count);
RunIterationViaStubs(config, iteration_stubs, thread_count);
continue;
}
RunIterationViaClient(config, client, thread_count, channel_count);
}
std::cout << overall.Annotations() << "\n";
return {};
}
protected:
// Note that by bypassing the Client layer we are not instantiating
// an `OptionsSpan`, so `CurrentOptions()` will be empty if called.
virtual std::vector<RowCpuSample> ViaStub(
Config const& config, int thread_count, int channel_count,
spanner::Database const& database,
std::shared_ptr<spanner_internal::SpannerStub> stub) = 0;
virtual std::vector<RowCpuSample> ViaClient(Config const& config,
int thread_count,
int channel_count,
spanner::Client client) = 0;
private:
void RunIterationViaStubs(
Config const& config,
std::vector<std::shared_ptr<spanner_internal::SpannerStub>> const& stubs,
int thread_count) {
std::vector<std::future<std::vector<RowCpuSample>>> tasks(thread_count);
int num_stubs = static_cast<int>(stubs.size());
int task_id = 0;
for (auto& t : tasks) {
auto const& client = stubs[task_id++ % num_stubs];
t = std::async(std::launch::async, [this, &config, thread_count,
num_stubs, client] {
return ViaStub(config, thread_count, num_stubs,
spanner::Database(config.project_id, config.instance_id,
config.database_id),
client);
});
}
for (auto& t : tasks) {
impl_.DumpSamples(t.get());
}
}
void RunIterationViaClient(Config const& config,
spanner::Client const& client, int thread_count,
int channel_count) {
std::vector<std::future<std::vector<RowCpuSample>>> tasks(thread_count);
for (auto& t : tasks) {
t = std::async(std::launch::async, [this, &config, &thread_count,
&channel_count, &client] {
return ViaClient(config, thread_count, channel_count, client);
});
}
for (auto& t : tasks) {
impl_.DumpSamples(t.get());
}
}
protected:
ExperimentImpl<Traits> impl_;
std::string table_name_;
};
/**
* Run an experiment to measure the CPU overhead of the client over raw gRPC.
*
* This experiments creates and populates a table with K rows, each row
* containing an (integer) key and 10 columns of the types defined by `Traits`.
* Then the experiment performs M iterations of:
* - Randomly select if it will do the work using the client library or raw
* gRPC
* - Then for N seconds read random rows
* - Measure the CPU time required by the previous step
*
* The values of K, M, N are configurable.
*/
template <typename Traits>
class ReadExperiment : public BasicExperiment<Traits> {
public:
explicit ReadExperiment(google::cloud::internal::DefaultPRNG generator)
: BasicExperiment<Traits>(generator, "Read") {}
protected:
std::vector<RowCpuSample> ViaStub(
Config const& config, int thread_count, int channel_count,
spanner::Database const& database,
std::shared_ptr<spanner_internal::SpannerStub> stub) override {
auto session = [&]() -> google::cloud::StatusOr<std::string> {
Status last_status;
for (int i = 0; i != 10; ++i) {
grpc::ClientContext context;
spanner_internal::RouteToLeader(context); // always for CreateSession
google::spanner::v1::CreateSessionRequest request{};
request.set_database(database.FullName());
auto response =
stub->CreateSession(context, google::cloud::Options{}, request);
if (response) return response->name();
last_status = response.status();
}
return last_status;
}();
if (!session) {
std::ostringstream os;
os << "SESSION ERROR = " << session.status();
this->impl_.LogError(std::move(os).str());
return {};
}
std::vector<RowCpuSample> samples;
// We expect about 50 reads per second per thread. Use that to estimate
// the size of the vector.
samples.reserve(
static_cast<std::size_t>(config.iteration_duration.count() * 50));
std::vector<std::string> const columns{"Key", "Data0", "Data1", "Data2",
"Data3", "Data4", "Data5", "Data6",
"Data7", "Data8", "Data9"};
for (auto start = std::chrono::steady_clock::now(),
deadline = start + config.iteration_duration;
start < deadline; start = std::chrono::steady_clock::now()) {
auto key = this->impl_.RandomKeySet(config);
auto timer = Timer::PerThread();
google::spanner::v1::ReadRequest request{};
request.set_session(*session);
request.mutable_transaction()
->mutable_single_use()
->mutable_read_only()
->Clear();
request.set_table(this->table_name_);
for (auto const& name : columns) {
request.add_columns(name);
}
*request.mutable_key_set() = spanner_internal::ToProto(key);
int row_count = 0;
google::spanner::v1::PartialResultSet result;
std::vector<google::protobuf::Value> row;
row.resize(columns.size());
auto stream = stub->StreamingRead(std::make_shared<grpc::ClientContext>(),
google::cloud::Options{}, request);
for (;;) {
google::spanner::v1::PartialResultSet result;
auto status = stream->Read(&result);
if (status.has_value()) {
auto const usage = timer.Sample();
samples.push_back(RowCpuSample{channel_count, thread_count, true,
row_count, usage.elapsed_time,
usage.cpu_time, *std::move(status)});
break;
}
if (result.chunked_value()) {
// We do not handle chunked values in the benchmark.
continue;
}
std::size_t index = 0;
for (auto& value : *result.mutable_values()) {
row[index] = std::move(value);
if (++index == columns.size()) {
++row_count;
index = 0;
}
}
}
}
return samples;
}
std::vector<RowCpuSample> ViaClient(Config const& config, int thread_count,
int channel_count,
spanner::Client client) override {
std::vector<std::string> const column_names{
"Key", "Data0", "Data1", "Data2", "Data3", "Data4",
"Data5", "Data6", "Data7", "Data8", "Data9"};
using T = typename Traits::native_type;
using RowType = std::tuple<std::int64_t, T, T, T, T, T, T, T, T, T, T>;
std::vector<RowCpuSample> samples;
// We expect about 50 reads per second per thread, so allocate enough
// memory to start.
samples.reserve(
static_cast<std::size_t>(config.iteration_duration.count() * 50));
for (auto start = std::chrono::steady_clock::now(),
deadline = start + config.iteration_duration;
start < deadline; start = std::chrono::steady_clock::now()) {
auto key = this->impl_.RandomKeySet(config);
auto timer = Timer::PerThread();
auto rows = client.Read(this->table_name_, key, column_names);
int row_count = 0;
Status status;
for (auto& row : spanner::StreamOf<RowType>(rows)) {
if (!row) {
status = std::move(row).status();
break;
}
++row_count;
}
auto const usage = timer.Sample();
samples.push_back(RowCpuSample{channel_count, thread_count, false,
row_count, usage.elapsed_time,
usage.cpu_time, std::move(status)});
}
return samples;
}
};
/**
* Run an experiment to measure the CPU overhead of the client over raw gRPC.
*
* This experiments creates and populates a table with `config.table_size` rows,
* each row containing an integer key and 10 columns of the types defined by
* `Traits`. Then the experiment performs `config.samples` iterations of:
* - Randomly pick if it will do the work using the client library or raw
* gRPC
* - Then for `config.iteration_duration` seconds SELECT random ranges of
* `config.query_size` rows
* - Measure the CPU time required by the previous step
*/
template <typename Traits>
class SelectExperiment : public BasicExperiment<Traits> {
public:
explicit SelectExperiment(google::cloud::internal::DefaultPRNG generator)
: BasicExperiment<Traits>(generator, "Select") {}
protected:
std::vector<RowCpuSample> ViaStub(
Config const& config, int thread_count, int channel_count,
spanner::Database const& database,
std::shared_ptr<spanner_internal::SpannerStub> stub) override {
auto session = [&]() -> google::cloud::StatusOr<std::string> {
Status last_status;
for (int i = 0; i != ExperimentImpl<Traits>::kColumnCount; ++i) {
grpc::ClientContext context;
spanner_internal::RouteToLeader(context); // always for CreateSession
google::spanner::v1::CreateSessionRequest request{};
request.set_database(database.FullName());
auto response =
stub->CreateSession(context, google::cloud::Options{}, request);
if (response) return response->name();
last_status = response.status();
}
return last_status;
}();
if (!session) {
std::ostringstream os;
os << "SESSION ERROR = " << session.status();
this->impl_.LogError(std::move(os).str());
return {};
}
std::vector<RowCpuSample> samples;
// We expect about 50 reads per second per thread. Use that to estimate
// the size of the vector.
samples.reserve(
static_cast<std::size_t>(config.iteration_duration.count() * 50));
auto const statement = CreateStatement();
for (auto start = std::chrono::steady_clock::now(),
deadline = start + config.iteration_duration;
start < deadline; start = std::chrono::steady_clock::now()) {
auto key = this->impl_.RandomKeySetBegin(config);
auto timer = Timer::PerThread();
google::spanner::v1::ExecuteSqlRequest request{};
request.set_session(*session);
request.mutable_transaction()
->mutable_single_use()
->mutable_read_only()
->Clear();
request.set_sql(statement);
auto begin_type_value = spanner_internal::ToProto(spanner::Value(key));
(*request.mutable_param_types())["begin"] =
std::move(begin_type_value.first);
(*request.mutable_params()->mutable_fields())["begin"] =
std::move(begin_type_value.second);
auto end_type_value =
spanner_internal::ToProto(spanner::Value(key + config.query_size));
(*request.mutable_param_types())["end"] = std::move(end_type_value.first);
(*request.mutable_params()->mutable_fields())["end"] =
std::move(end_type_value.second);
int row_count = 0;
google::spanner::v1::PartialResultSet result;
std::vector<google::protobuf::Value> row;
row.resize(ExperimentImpl<Traits>::kColumnCount);
auto stream =
stub->ExecuteStreamingSql(std::make_shared<grpc::ClientContext>(),
google::cloud::Options{}, request);
for (;;) {
google::spanner::v1::PartialResultSet result;
auto status = stream->Read(&result);
if (status.has_value()) {
auto const usage = timer.Sample();
samples.push_back(RowCpuSample{channel_count, thread_count, true,
row_count, usage.elapsed_time,
usage.cpu_time, *std::move(status)});
break;
}
if (result.chunked_value()) {
// We do not handle chunked values in the benchmark.
continue;
}
std::size_t index = 0;
for (auto& value : *result.mutable_values()) {
row[index] = std::move(value);
if (++index == ExperimentImpl<Traits>::kColumnCount) {
++row_count;
index = 0;
}
}
}
}
return samples;
}
std::vector<RowCpuSample> ViaClient(Config const& config, int thread_count,
int channel_count,
spanner::Client client) override {
auto const statement = CreateStatement();
using T = typename Traits::native_type;
using RowType = std::tuple<T, T, T, T, T, T, T, T, T, T>;
std::vector<RowCpuSample> samples;
// We expect about 50 reads per second per thread, so allocate enough
// memory to start.
samples.reserve(
static_cast<std::size_t>(config.iteration_duration.count() * 50));
for (auto start = std::chrono::steady_clock::now(),
deadline = start + config.iteration_duration;
start < deadline; start = std::chrono::steady_clock::now()) {
auto key = this->impl_.RandomKeySetBegin(config);
auto timer = Timer::PerThread();
auto rows = client.ExecuteQuery(spanner::SqlStatement(
statement, {{"begin", spanner::Value(key)},
{"end", spanner::Value(key + config.query_size)}}));
int row_count = 0;
Status status;
for (auto& row : spanner::StreamOf<RowType>(rows)) {
if (!row) {
status = std::move(row).status();
break;
}
++row_count;
}
auto const usage = timer.Sample();
samples.push_back(RowCpuSample{channel_count, thread_count, false,
row_count, usage.elapsed_time,
usage.cpu_time, std::move(status)});
}
return samples;
}
std::string CreateStatement() const {
std::string sql = "SELECT";
char const* sep = " ";
for (int i = 0; i != ExperimentImpl<Traits>::kColumnCount; ++i) {
sql += sep;
sql += "Data" + std::to_string(i);
sep = ", ";
}
sql += " FROM ";
sql += this->table_name_;
sql += " WHERE Key >= @begin AND Key < @end";
return sql;
}
};
/**
* Run an experiment to measure the CPU overhead of the client over raw gRPC.
*
* This experiments creates and populates a table with K rows, each row
* containing an (integer) key and 10 columns of the types defined by `Traits`.
* Then the experiment performs M iterations of:
* - Randomly select if it will read using the client library or raw gRPC.
* - Then for N seconds update random rows
* - Measure the CPU time required by the previous step
*
* The values of K, M, N are configurable.
*/
template <typename Traits>
class UpdateExperiment : public BasicExperiment<Traits> {
public:
explicit UpdateExperiment(google::cloud::internal::DefaultPRNG generator)
: BasicExperiment<Traits>(generator, "Update") {}
protected:
std::vector<RowCpuSample> ViaStub(
Config const& config, int thread_count, int channel_count,
spanner::Database const& database,
std::shared_ptr<spanner_internal::SpannerStub> stub) override {
std::string const statement = CreateStatement();
auto session = [&]() -> google::cloud::StatusOr<std::string> {
Status last_status;
for (int i = 0; i != 10; ++i) {
grpc::ClientContext context;
spanner_internal::RouteToLeader(context); // always for CreateSession
google::spanner::v1::CreateSessionRequest request{};
request.set_database(database.FullName());
auto response =
stub->CreateSession(context, google::cloud::Options{}, request);
if (response) return response->name();
last_status = response.status();
}
return last_status;
}();
if (!session) {
std::ostringstream os;
os << "SESSION ERROR = " << session.status();
this->impl_.LogError(std::move(os).str());
return {};
}
std::vector<RowCpuSample> samples;
// We expect about 50 reads per second per thread. Use that to estimate
// the size of the vector.
samples.reserve(
static_cast<std::size_t>(config.iteration_duration.count() * 50));
for (auto start = std::chrono::steady_clock::now(),
deadline = start + config.iteration_duration;
start < deadline; start = std::chrono::steady_clock::now()) {
auto const key = this->impl_.RandomKey(config);
using T = typename Traits::native_type;
std::vector<T> const values{
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
};
auto timer = Timer::PerThread();
google::spanner::v1::ExecuteSqlRequest request{};
request.set_session(*session);
request.mutable_transaction()
->mutable_begin()
->mutable_read_write()
->Clear();
request.set_sql(statement);
auto key_type_value = spanner_internal::ToProto(spanner::Value(key));
(*request.mutable_param_types())["key"] = std::move(key_type_value.first);
(*request.mutable_params()->mutable_fields())["key"] =
std::move(key_type_value.second);
for (int i = 0; i != 10; ++i) {
auto tv = spanner_internal::ToProto(spanner::Value(values[i]));
auto name = "v" + std::to_string(i);
(*request.mutable_param_types())[name] = std::move(tv.first);
(*request.mutable_params()->mutable_fields())[name] =
std::move(tv.second);
}
int row_count = 0;
std::string transaction_id;
google::cloud::Status status;
{
grpc::ClientContext context;
auto response =
stub->ExecuteSql(context, google::cloud::Options{}, request);
if (response) {
row_count =
static_cast<int>(response->stats().row_count_lower_bound());
transaction_id = response->metadata().transaction().id();
} else {
status = std::move(response).status();
}
}
if (status.ok()) {
grpc::ClientContext context;
google::spanner::v1::CommitRequest commit_request;
commit_request.set_session(*session);
commit_request.set_transaction_id(transaction_id);
auto response =
stub->Commit(context, google::cloud::Options{}, commit_request);
if (!response) status = std::move(response).status();
}
auto const usage = timer.Sample();
samples.push_back(RowCpuSample{channel_count, thread_count, true,
row_count, usage.elapsed_time,
usage.cpu_time, status});
}
return samples;
}
std::vector<RowCpuSample> ViaClient(Config const& config, int thread_count,
int channel_count,
spanner::Client client) override {
std::string const statement = CreateStatement();
std::vector<RowCpuSample> samples;
// We expect about 50 reads per second per thread, so allocate enough
// memory to start.
samples.reserve(
static_cast<std::size_t>(config.iteration_duration.count() * 50));
for (auto start = std::chrono::steady_clock::now(),
deadline = start + config.iteration_duration;
start < deadline; start = std::chrono::steady_clock::now()) {
auto const key = this->impl_.RandomKey(config);
using T = typename Traits::native_type;
std::vector<T> const values{
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
this->impl_.GenerateRandomValue(), this->impl_.GenerateRandomValue(),
};
auto timer = Timer::PerThread();
std::unordered_map<std::string, spanner::Value> const params{
{"key", spanner::Value(key)}, {"v0", spanner::Value(values[0])},
{"v1", spanner::Value(values[1])}, {"v2", spanner::Value(values[2])},
{"v3", spanner::Value(values[3])}, {"v4", spanner::Value(values[4])},
{"v5", spanner::Value(values[5])}, {"v6", spanner::Value(values[6])},
{"v7", spanner::Value(values[7])}, {"v8", spanner::Value(values[8])},
{"v9", spanner::Value(values[9])},
};
int row_count = 0;
auto commit_result =
client.Commit([&](spanner::Transaction const& txn)
-> google::cloud::StatusOr<spanner::Mutations> {
auto result = client.ExecuteDml(
txn, spanner::SqlStatement(statement, params));
if (!result) return std::move(result).status();
row_count = static_cast<int>(result->RowsModified());
return spanner::Mutations{};
});
auto const usage = timer.Sample();
samples.push_back(RowCpuSample{
channel_count, thread_count, false, row_count, usage.elapsed_time,
usage.cpu_time, std::move(commit_result).status()});
}
return samples;
}
std::string CreateStatement() const {
std::string sql = "UPDATE " + this->table_name_;