Skip to content

Instantly share code, notes, and snippets.

@ijklr
Created July 9, 2016 02:14
Show Gist options
  • Save ijklr/bfa257344aa65951b60956a38fe45a89 to your computer and use it in GitHub Desktop.
Save ijklr/bfa257344aa65951b60956a38fe45a89 to your computer and use it in GitHub Desktop.
C++ STL std::copy benchmark
#include <iostream>
#include <random>
#include <chrono>
#include <sstream>
#include <algorithm>
#include <vector>
#include <string>
#include <ostream>
#include <cstring>
using namespace std;
template <class InputIterator, class OutputIterator>
void mycopy(InputIterator first, InputIterator last, OutputIterator result)
{
while(first != last) {
*result = *first;
++result;
++first;
}
}
void p(string msg) {
cout <<msg<<endl;
}
template <class T>
class Foo {
public:
using difference_type = ptrdiff_t;
using value_type = T;
using pointer = const T*;
using reference = const T&;
using iterator_category = std::forward_iterator_tag;
Foo() { p("default constructor");}
Foo(const Foo &foo) { p("copy constructor");}
Foo& operator=(int i)
{
ostringstream oss;
oss<<"receiving i="<<i;
p(oss.str());
return *this;
}
Foo& operator=(const Foo &foo)
{
p("assignment operator");
return *this;
}
Foo& operator*() {
p("deference operator");
return *this;
}
const Foo operator++(int)
{
p("post increment operator");
return *this;
}
Foo& operator++()
{
p("pre increment operator");
return *this;
}
~Foo()
{
p("Foo destructor.");
}
};
class StopWatch {
public:
void start()
{
t1 = std::chrono::steady_clock::now();
}
void stop()
{
t2 = std::chrono::steady_clock::now();
}
double count()
{
std::chrono::duration<double> d = t2 - t1;
return d.count();
}
private:
std::chrono::steady_clock::time_point t1, t2;
};
int main()
{
/*
Foo<int> f;
vector<int> v1{1,2};
p("calling copy------------------");
copy(begin(v1), end(v1), f);
p("calling mycopy================");
mycopy(begin(v1), end(v1), f);
*/
using Elem = char;
using Container = vector<Elem>;
Container v2(1000000,0);
Container v3(1000000,0);
Container v4(1000000,0);
Container v5(1000000,0);
default_random_engine generator;
uniform_int_distribution<int> distribution(0,100);
for(size_t i = 0; i < v2.size(); ++i) {
v2[i] = distribution(generator);
}
StopWatch sw;
sw.start();
copy(begin(v2), end(v2), begin(v3));
sw.stop();
cout<<"copy time="<<sw.count()<<endl;
sw.start();
mycopy(begin(v2), end(v2), begin(v4));
sw.stop();
cout<<"mycopy time="<<sw.count()<<endl;
sw.start();
memcpy(&v5[0], &v2[0], v2.size() * sizeof(Elem));
sw.stop();
cout<<"memcpy time="<<sw.count()<<endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment