Skip to content

Instantly share code, notes, and snippets.

@eabase
Forked from silahian/MemoryAllocationHFT.cpp
Created October 23, 2020 18:54
Show Gist options
  • Save eabase/6dae95d977648be8de3d2c39be904f7e to your computer and use it in GitHub Desktop.
Save eabase/6dae95d977648be8de3d2c39be904f7e to your computer and use it in GitHub Desktop.
Pre allocated vs dynamic arrays performance for low latency / high frequency trading systems
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <time.h>
// ***********************************
// This is for measuring CPU clocks
#if defined(__i386__)
static __inline__ unsigned long long rdtsc(void)
{
unsigned long long int x;
__asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
return x;
}
#elif defined(__x86_64__)
static __inline__ unsigned long long rdtsc(void)
{
unsigned hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}
#endif
// ***********************************
using namespace std;
struct BookPrice
{
int size;
double price;
};
vector<BookPrice> aDynamic;
vector<BookPrice> aPreallocated(10);
void AddRemoveDynamically(int type, BookPrice& b);
void AddRemovePre(int type, BookPrice& b);
int totAddsDyn=0, totDelsDyn=0;
int totAddsFix=0, totDelsFix=0;
int main()
{
int sampleRun = 1000000;
double sumRunDyn = 0;
double sumRunFix = 0;
for(int i=0; i<sampleRun; i++)
{
BookPrice b;
b.price=rand() % 10 + 1; //random 1 to 10
int type = (rand() % 2) + 1; //random 1 to 2
auto ini = rdtsc();
AddRemoveDynamically(type, b);
auto end = rdtsc();
sumRunDyn += end-ini;
ini = rdtsc();
AddRemovePre(type, b);
end = rdtsc();
sumRunFix += end-ini;
}
cout << "Dynamic Took: "<< sumRunDyn/sampleRun << endl;
cout << "Pre-allocated Took: "<< sumRunFix/sampleRun << endl;
cout << "Difference: % " << 100 * ((sumRunDyn/sampleRun) - (sumRunFix/sampleRun)) / (sumRunFix/sampleRun) << endl;
}
/*
ADD type=1
DELETE type=2
*/
void AddRemoveDynamically(int type, BookPrice& b)
{
if (type == 1)
{
totAddsDyn++;
//add element
aDynamic.push_back(b);
}
else if (type == 2)
{
totDelsDyn++;
aDynamic.erase(std::remove_if(aDynamic.begin(), aDynamic.end(), [&](BookPrice const & p) {return p.price == b.price;}),aDynamic.end());
}
std::sort(aDynamic.begin(), aDynamic.end(), [&](BookPrice& ltd, BookPrice& rtd){ return ltd.price < rtd.price; });
}
void AddRemovePre(int type, BookPrice& b)
{
if (type == 1)
{
totAddsFix++;
//always rewrite first item, since newer
aPreallocated[0] = b;
}
else if (type == 2)
{
totDelsFix++;
auto it= find_if(aPreallocated.begin(), aPreallocated.end(), [&](BookPrice const & p) {return p.price == b.price;});
if (it != aPreallocated.end())
{
it->price=0;
it->size=0;
}
}
std::sort(aPreallocated.begin(), aPreallocated.end(), [&](BookPrice& ltd, BookPrice& rtd){ return ltd.price < rtd.price; });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment