Thanks to this thread I managed to get a massive speed up in some production code of mine by employing some ternary operators:
I have a large vector of coordinates and need to find the bounding box of them. This was the old code:
Simple enough, I changed the code to this:
I tested 10,000 loops of an example vector.
The old code took: 142.6 seconds (average of 3 trials)
The new code took: 27.3 (average of 5 trials)
Co,piled with gcc 4.81 and O3 optimization
5x speed up and to me the code is still very readable.
I have a large vector of coordinates and need to find the bounding box of them. This was the old code:
Code:
//First initialize bbox to first value in vecotr points (not shown)
/// Loop...
for (size_t i = 1; i < points.size(); ++i)
{
const Point& p = points[i];
if (p.m_lon < m_min.x)
m_min.x = p.m_lon;
else if (p.m_lon > m_max.x)
m_max.x = p.m_lon;
if (p.m_lat < m_min.y)
m_min.y = p.m_lat;
else if (p.m_lat > m_max.y)
m_max.y = p.m_lat;
}
Simple enough, I changed the code to this:
Code:
for (size_t i = 1; i < points.size(); ++i)
{
const Point& p = points[i];
m_min.x = p.m_lon < m_min.x ? p.m_lon : m_min.x;
m_max.x = p.m_lon > m_max.x ? p.m_lon : m_max.x;
m_min.y = p.m_lat < m_min.y ? p.m_lat : m_min.y;
m_max.y = p.m_lat > m_max.y ? p.m_lat : m_max.y;
}
I tested 10,000 loops of an example vector.
The old code took: 142.6 seconds (average of 3 trials)
The new code took: 27.3 (average of 5 trials)
Co,piled with gcc 4.81 and O3 optimization
5x speed up and to me the code is still very readable.