Last active
April 9, 2023 22:56
-
-
Save bwedding/2a6015df8a054b686e15e5dfd50c2cad to your computer and use it in GitHub Desktop.
Cleanup of UncleBobs Code
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
#include <iostream> | |
#include <stdlib.h> | |
#include <chrono> | |
#include <vector> | |
#include <format> | |
using namespace std; | |
using namespace std::chrono; | |
const unsigned long N = 999983L; | |
static int vs[N]{}; | |
static std::vector<long> counters(10); | |
inline long ms() | |
{ | |
auto now = high_resolution_clock::now(); | |
auto now_since_epoch = now.time_since_epoch(); | |
auto now_in_ms = duration_cast<milliseconds>(now_since_epoch); | |
return static_cast<long>(now_in_ms.count() % (static_cast<long long>(86400) * 1000)); | |
} | |
void do_s(int x) | |
{ | |
switch (x) | |
{ | |
case 0: counters[0]++; break; | |
case 3: counters[3]++; break; | |
case 1: counters[1]++; break; | |
case 9: counters[9]++; break; | |
case 4: counters[4]++; break; | |
case 5: counters[5]++; break; | |
case 6: counters[6]++; break; | |
case 2: counters[2]++; break; | |
case 7: counters[7]++; break; | |
case 8: counters[8]++; break; | |
} | |
} | |
void s_lup(int n) | |
{ | |
for (int i = 0; i < n; i++) | |
{ | |
do_s(vs[i % N]); | |
} | |
} | |
class B | |
{ | |
public: | |
virtual void inc() = 0; | |
}; | |
static std::vector<B*> bs(N); | |
class D : public B | |
{ | |
const int id = 0; | |
public: | |
D(int x) : id(x){} | |
virtual void inc() { counters[id]++; } | |
}; | |
void do_c(B& b) | |
{ | |
b.inc(); | |
} | |
void c_lup(int n) | |
{ | |
for (int i = 0; i < n; i++) | |
{ | |
do_c(*bs[i % N]); | |
} | |
} | |
int main(int ac, char** av) | |
{ | |
srand(time(nullptr)); | |
const auto n = 100000000L; | |
for (auto i = 0; i < N; i++) | |
{ | |
auto rnd = rand() % 10; | |
vs[i] = rnd; | |
bs[i] = new D(rnd); | |
} | |
std::fill(counters.begin(), counters.end(), 0); | |
auto start_s = ms(); | |
s_lup(n); | |
auto end_s = ms(); | |
cout << "s-lup counts: " << endl; | |
for (const auto &count : counters) | |
cout << count << endl; | |
std::fill(counters.begin(), counters.end(), 0); | |
auto start_c = ms(); | |
c_lup(n); | |
auto end_c = ms(); | |
cout << "c-lup counts: " << endl; | |
for (const auto& count : counters) | |
cout << count << endl; | |
auto s_time = (end_s - start_s); | |
auto c_time = (end_c - start_c); | |
auto diff = (c_time - s_time); | |
auto s_ns = (s_time * 1000000.0) / n; | |
auto c_ns = (c_time * 1000000.0) / n; | |
auto diff_ns = (diff * 1000000.0) / n; | |
std::cout << std::format("switch-ns: {:g}, class-ns: {:g}, diff-ns: {:g}, factor: {:g}\n", s_ns, c_ns, diff_ns, c_ns / s_ns); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment