Created
February 20, 2015 07:40
-
-
Save cruppstahl/78a57cdf937bca3d062c to your computer and use it in GitHub Desktop.
Micro benchmark memmove vs memcpy
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
// compile with | |
// g++ -Wall microbench.cc -lboost_system -lboost_chrono -Ofast -o microbench | |
// | |
#include <string.h> | |
#include <iostream> | |
#include <boost/chrono.hpp> | |
#include <iostream> | |
#include <iomanip> | |
using namespace boost::chrono; | |
// based on | |
// http://www.boost.org/doc/libs/1_54_0/libs/chrono/example/await_keystroke.cpp | |
template<class Clock> | |
class Timer | |
{ | |
typename Clock::time_point start; | |
public: | |
Timer() | |
: start(Clock::now()) { | |
} | |
typename Clock::duration elapsed() const { | |
return (Clock::now() - start); | |
} | |
double seconds() const { | |
return (elapsed().count() * | |
((double)Clock::period::num / Clock::period::den)); | |
} | |
}; | |
#define BUFFERSIZE (100 * 1024 * 1024) // 100 mb | |
#define LOOPS 10 | |
#define MAXSTRIDE 128 | |
int main() | |
{ | |
char *b1 = (char *)::malloc(BUFFERSIZE + MAXSTRIDE); | |
char *b2 = (char *)::malloc(BUFFERSIZE + MAXSTRIDE); | |
::memset(b1, 0, BUFFERSIZE + MAXSTRIDE); | |
// Each test is performed |LOOP| times; the average run-time is then printed. | |
// Test memcpy() by copying from buffer b1 to b2 | |
Timer<boost::chrono::high_resolution_clock> t; | |
for (int i = 0; i < LOOPS; i++) | |
memcpy(b2, b1, BUFFERSIZE); | |
double seconds = t.seconds(); | |
std::cout << "memcpy " << (seconds / LOOPS) << std::endl; | |
// Test memmove() by inserting a small gap at the beginning of the buffer | |
for (int stride = 2; stride <= MAXSTRIDE; stride *= 2) { | |
Timer<boost::chrono::high_resolution_clock> t; | |
for (int i = 0; i < LOOPS; i++) | |
memmove(b1 + stride, b1, BUFFERSIZE); | |
double seconds = t.seconds(); | |
std::cout << "memmove (" << std::setfill('0') << std::setw(3) | |
<< stride << ") " << (seconds / LOOPS) << std::endl; | |
} | |
::free(b1); | |
::free(b2); | |
return (0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment