#include // std::copy #include // time measurement #include // std::atol #include // std::memcpy #include // std::cout const std::string usage = "call ./std-copy "; /* * do a simple performance measurement for std::copy * as opposed to copying using a for loop and using memcpy */ int main(int argc, char** argv) { if(argc < 3) { std::cout << usage << "\n"; return EXIT_FAILURE; } int array_size = std::atol(argv[1]); if(0 >= array_size) { std::cout << usage << "\n"; return EXIT_FAILURE; } int iterations = std::atol(argv[2]); if(0 >= iterations) { std::cout << usage << "\n"; return EXIT_FAILURE; } /* * create some source content that we will be copying */ long* source = new long[array_size]; for(int i = 1; i < array_size; i++) source[i] = i*i - 1; /* * this is where we will be copying to */ long* target = new long[array_size]; auto t0 = std::chrono::high_resolution_clock::now(); /* * copy element by element using a for loop */ for(int i = 0; i < iterations; i++) for(int j = 0; j < array_size; j++) target[j] = source[j]; auto t1 = std::chrono::high_resolution_clock::now(); auto delta_t01 = std::chrono::duration_cast(t1-t0).count(); std::cout << "element-wise:\t" << 1.0e-06*delta_t01 << "\n"; /* * contiguous copy in C style using std::memcpy */ for(int i = 0; i < iterations; i++) std::memcpy(target, source, array_size * sizeof(long)); auto t2 = std::chrono::high_resolution_clock::now(); auto delta_t12 = std::chrono::duration_cast(t2-t1).count(); std::cout << "std::memcpy:\t" << 1.0e-06*delta_t12 << "\n"; /* * contiguous copy in C++ style using std::copy */ for(int i = 0; i < iterations; i++) std::copy(source, source + array_size, target); auto t3 = std::chrono::high_resolution_clock::now(); auto delta_t23 = std::chrono::duration_cast(t3-t2).count(); std::cout << "std::copy:\t" << 1.0e-06*delta_t23 << "\n"; delete[] source; delete[] target; }