Skip to content

Instantly share code, notes, and snippets.

@valexey
Created August 3, 2020 14:36
Show Gist options
  • Save valexey/d012af369fa4913cc4e0fad24ec3253f to your computer and use it in GitHub Desktop.
Save valexey/d012af369fa4913cc4e0fad24ec3253f to your computer and use it in GitHub Desktop.
#include <iostream>
#include <thread>
#include <chrono>
#include <memory>
#include <vector>
#include <cmath>
#include <array>
#include <iterator>
constexpr int size = 100'000'000;
auto single_thread()
{
auto t0 = std::chrono::steady_clock::now();
std::vector<float> arr(size, 1.0f);
for (int i=0; i<arr.size(); ++i) {
arr[i] = arr[i] * sin(0.2 + i/5.0)*cos(0.2 + i/5.0) * cos(0.4 + i/2.0);
}
auto t1 = std::chrono::steady_clock::now();
std::cout << "single: " << std::chrono::duration_cast<std::chrono::milliseconds>(t1-t0).count() << std::endl;
return arr;
}
auto double_thread()
{
auto t0 = std::chrono::steady_clock::now();
std::vector<float> arr(size, 1.0f);
auto h = size/2;
std::vector<float> arr1(h);
std::copy_n(arr.begin(), h, arr1.begin());
std::vector<float> arr2(h);
std::copy_n(arr.begin()+h, h, arr2.begin());
std::thread th1([&arr1, h](){
for (int i=0; i<arr1.size(); i++)
arr1[i] = arr1[i] * sin(0.2 + i/5.0)*cos(0.2 + i/5.0) * cos(0.4 + i/2.0);
});
std::thread th2([&arr2, h](){
for (int i=0; i<arr2.size(); i++) {
int o = i+h;
arr2[i] = arr2[i] * sin(0.2 + o/5.0)*cos(0.2 + o/5.0) * cos(0.4 + o/2.0);
}
});
th1.join();
th2.join();
std::copy_n(arr1.begin(), h, arr.begin());
std::copy_n(arr2.begin(), h, arr.begin()+h);
auto t1 = std::chrono::steady_clock::now();
std::cout << "double: " << std::chrono::duration_cast<std::chrono::milliseconds>(t1-t0).count() << std::endl;
return arr;
}
int main()
{
for (int i=0; i<100; ++i) {
auto arr1 = single_thread();
auto arr2 = double_thread();
std::cout << (arr1==arr2) << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment