Last active
April 2, 2020 21:58
-
-
Save gopi487krishna/4e5ded08e5949d1d34b4b2fcdcc0bc25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// string_view_vs_string_test.cpp : This file contains the 'main' function. Program execution begins and ends there. | |
// | |
#include <iostream> | |
#include <vector> | |
#include <fstream> | |
#include <string_view> | |
#include <unordered_map> | |
#include <chrono> | |
#include <benchmark/benchmark.h> | |
// This is not optimized and dosent have to be | |
std::vector<std::string> read_header_raw(const std::string& filename) { | |
std::vector<std::string> raw_cards; | |
std::ifstream input_file_stream(filename); | |
if (input_file_stream.is_open()) { | |
std::istreambuf_iterator<char> inp_iter(input_file_stream); // Iterators for traversing the entire stream | |
std::istreambuf_iterator<char> end_of_file; | |
while (inp_iter != end_of_file) { | |
std::string raw_card; | |
for (int i = 0; i < 80; i++) raw_card.push_back(*inp_iter++); | |
raw_cards.push_back(raw_card); | |
} | |
return raw_cards; | |
} | |
} | |
// String_View based | |
inline std::string_view getKey(std::string_view card) { | |
std::string_view my_str = card; | |
return my_str.substr(0, 8); // Returns a view rather than actual string | |
//return std::string_view(card.data(), 8); | |
} | |
// String based | |
inline std::string getKey_str(const std::string& card) { | |
return card.substr(0, 8); | |
} | |
static void TEST_STRING(benchmark::State& state) { | |
// Runs only once | |
auto raw_cards = read_header_raw("FITS_HEADER.txt"); | |
int count = 0; | |
std::unordered_map<std::string, size_t> fast_lookup; | |
for (auto _ : state) { | |
for (auto&raw_card : raw_cards) { | |
benchmark::DoNotOptimize(fast_lookup[getKey_str(raw_card)] = count++); | |
} | |
} | |
} | |
static void TEST_STRING_VIEW(benchmark::State& state) { | |
// Runs only once | |
auto raw_cards = read_header_raw("FITS_HEADER.txt"); | |
int count = 0; | |
std::unordered_map<std::string_view, size_t> fast_lookup; | |
for (auto _ : state) { | |
for (auto&raw_card : raw_cards) { | |
benchmark::DoNotOptimize(fast_lookup[getKey(raw_card)] = count++); | |
} | |
} | |
} | |
BENCHMARK(TEST_STRING)->Unit(benchmark::kMicrosecond); | |
BENCHMARK(TEST_STRING_VIEW)->Unit(benchmark::kMicrosecond); | |
BENCHMARK_MAIN(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment