Skip to content

Instantly share code, notes, and snippets.

@adamkewley
Created February 18, 2020 16:11
Show Gist options
  • Save adamkewley/1608fdc722c71caa2bc6cbf326851e53 to your computer and use it in GitHub Desktop.
Save adamkewley/1608fdc722c71caa2bc6cbf326851e53 to your computer and use it in GitHub Desktop.
#include <vector>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cerrno>
#include <chrono>
#include <string>
using std::chrono::time_point;
using std::chrono::microseconds;
using std::chrono::duration_cast;
namespace {
std::vector<uint8_t> read_entirely_manual(const std::string& pth) {
std::ifstream strm{pth, std::ios::binary};
strm.exceptions(std::ifstream::badbit);
constexpr size_t read_sz = 8192;
std::vector<uint8_t> out(read_sz);
auto bytes_read = 0;
while (strm.read(reinterpret_cast<char*>(out.data() + bytes_read), read_sz)) {
auto count = strm.gcount();
bytes_read += count;
out.resize(out.size() + count);
}
bytes_read += strm.gcount();
out.resize(bytes_read);
return out;
}
std::vector<uint8_t> read_entirely_clean(const std::string& pth) {
auto strm = std::ifstream{pth, std::ios::in | std::ios::binary};
strm.exceptions(std::ifstream::failbit);
return std::vector<std::uint8_t>(std::istreambuf_iterator<char>{strm}, {});
}
}
int main(int argc, char** argv) {
int num_paths = argc - 1;
char** paths = argv + 1;
for (int i = 0; i < num_paths; i++) {
const char* path = paths[i];
auto manual_start = std::chrono::high_resolution_clock::now();
std::vector<uint8_t> manual = read_entirely_manual(path);
auto manual_dur =
duration_cast<microseconds>(std::chrono::high_resolution_clock::now() - manual_start);
auto clean_start = std::chrono::high_resolution_clock::now();
std::vector<uint8_t> clean = read_entirely_clean(path);
auto clean_dur =
duration_cast<microseconds>(std::chrono::high_resolution_clock::now() - clean_start);
if (manual != clean) {
throw std::runtime_error{"outputs do not match: implementations differ!"};
}
std::cout << path << " " << manual.size() << " manual " << manual_dur.count() << ", clean " << clean_dur.count() << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment