Efficient implementation and �code optimization
Yevhen Zadorozhnii
�The summer programming school Uzhhorod - 2020
League 1. Day 4.
Introduction
Why is this topic important?
But...!
Being effective is about doing the right things, �while being efficient is about doing things right.
The main principles of efficient implementation
C++ STL features
std::vector
std::vector
std::map / std::set
std::map / std::set
int value = 0;
set<int> s;
if (!s.count(value)) {
s.insert(value);
// do_something_else
}
std::unordered_map / std::unordered_set
std::string
std::vector<bool>
std::bitset
std::array
Fast Input/Output
Fast Input/Output
Fast Input/Output
Example of custom input implementation
template<class T = int>
T readInt() {
const int BSIZE = 4096;
static char buffer[BSIZE];
static char* bptr = buffer + BSIZE;
auto getChar = []() {
if (bptr == buffer + BSIZE) {
std::memset(buffer, 0, BSIZE);
cin.read(buffer, BSIZE);
bptr = buffer;
}
return *bptr++;
};
char c = getChar(); while (c && (c < '0' || c > '9') && c != '-') c = getChar();
bool minus = false;
if (c == '-') minus = true, c = getChar();
T res = 0;
while (c >= '0' && c <= '9') { res = res * 10 + c - '0'; c = getChar(); }
return minus ? -res : res;
}
Efficient memory
Memory allocations
Memory access
Hints on work with memory
Hints on work with memory
Code optimization
Introduction
Operations cost
Vectorization
Vectorization
Helping the compiler to vectorize your code
Helping the compiler