Skip to content

Instantly share code, notes, and snippets.

@ffoxin
Last active August 29, 2015 13:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ffoxin/8705982 to your computer and use it in GitHub Desktop.
Save ffoxin/8705982 to your computer and use it in GitHub Desktop.
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
inline size_t calc(const size_t n, const size_t i, const size_t j)
{
volatile size_t ret;
if (i > j)
{
if (i + j < n)
{
ret = (n - (j + 1)) * (j + 1) * 4 - (i - (j + 1));
}
else
{
ret = (n - (n - i)) * (n - i) * 4 - (i - (n - i)) - (j - n + i + 1);
}
}
else
{
if (i + j < n)
{
ret = i * (n - i) * 4 - (i - (n - i)) + i + j - n + 1;
}
else
{
ret = (n - (n - j - 1)) * (n - j - 1) * 4 + (j - (n - j)) + i + (j - n) + 3;
}
}
return ret;
}
void calc_sq_part(const size_t n, const size_t i_from, const size_t i_till)
{
for (size_t i = i_from; i < i_till; ++i)
{
for (size_t j = 0; j < n; ++j)
{
calc(n, i, j);
}
}
}
int main()
{
const size_t n = 10000;
unsigned thread_count = thread::hardware_concurrency() * 2;
if (thread_count == 0)
{
thread_count = 1;
}
const size_t n_per_thread = n / thread_count;
vector<thread> tpool;
tpool.reserve(thread_count);
for (size_t i = 0; i < n; i += n_per_thread)
{
tpool.push_back(thread(calc_sq_part, n, i, i + n_per_thread));
}
clock_t c_start = clock();
auto t_start = chrono::high_resolution_clock::now();
for_each(tpool.begin(), tpool.end(), [](thread& tr)
{
tr.join();
});
clock_t c_end = clock();
auto t_end = chrono::high_resolution_clock::now();
cout << "Square size: " << n << endl;
cout << "CPU time: "
<< setprecision(4)
<< double(c_end - c_start) / CLOCKS_PER_SEC
<< " sec" << endl;
cout << "Real time: "
<< setprecision(4)
<< double(chrono::duration_cast<chrono::milliseconds>(t_end - t_start).count()) / 1000
<< " sec" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment