C++ London Meetup: Type Punning and Counting Nanoseconds

September’s C++ London Meetup featured two talks: Type Punning by Timur Doumler and Counting Nanoseconds by David Gross of Optiver. Optiver were the generous sponsors of this event, hosted at SkillsMatter near Moorgate.

Counting Nanoseconds

Optiver are based in Amsterdam and operate in the High-Frequency Trading sphere. Naturally, they need code to be fast in order to take trades more quickly than their competitors, but the benefits of fast code also extend to minimising energy costs in data centres and extending battery life on portable devices for other applications. David Gross spoke about micro-benchmarking – boiling code down to very small numbers of instructions to aid comparisons and improve performance. The caveat was that it’s always vital to measure performance in production using real data as well as doing this offline, low-level analysis against potted test cases. David warning against relying on the high-resolution clock which can be problematic (may not be steady and may not have the resolution you need). He often uses Intel Time Stamp Counter (TSC), although that’s not the original intention of that metric.

Type Punning

Timur is fascinated by the ability to take an object and treat it as another type in C++. Yet, in many cases, this results in undefined behaviour. For example:

class Gizmo {
  virtual void print(){ std::cout << "Gizmo\n"; }
class Widget {
  virtual void print(){ std::cout << "Widget\n"; }
Gizmo g;
Widget* w = (Widget*)(&g);

The behaviour of this code is undefined, because Widget and Gizmo are unrelated, although both have a virtual print function, so the virtual function table is the same. The standard says that you can’t call a method on a reinterpret-cast’d object – you can only cast it back to the actual type of the object. But on most compilers tried by Timur, the code runs and prints “Gizmo”. He referenced the CppCon 2018 talk, Undefined Behaviour is Not an Error.

Other examples concerned how to share memory across multiple data types, such as treating 4 bytes as either a char array or as a float. Even using a union can result in undefined behaviour, because only one member is ‘alive’ at a time. In order to write portable code, you must consider aliasing rules, object lifetime rules and alignment rules. In same cases, you can use C++17’s std::memcpy to ensure alignment (but only if the types are the same size and trivially copyable). std::bit_cast is coming with C++20. And in C++23, there’s a proposal for std::start_lifetime_as(char[]) to implicitly create objects, for example when reading from a buffer.

The video for this talk is available on SkillsCast.

Leave a comment

Filed under C++, C++ Code, Meetup, Programming

Book Review: Rendezvous with Rama, Arthur C. Clarke

Suppose an alien craft was detected in the solar system, something like Oumuamua, little understood with a strange trajectory. Would the United Nations investigate it or just blow it up as a threat? That’s where we begin the story in this book – the options are narrowed down because only one spacecraft is close enough to be able to intercept the object (named as Rama), and the United Planets agree to gather as much information as possible. As you would expect, there are disagreements with the approach and Mercury in particular thinks destruction is the way to go.

The story concentrates on the strange geography of the craft – 50km long on its axis, 20km across and rotating every 4 minutes. Yet it has an ocean around the centre of the axis, cities spread out across the plains and few clues as to the nature of the constructors of the craft. It’s a great book, full of ideas that must have been mind-blowing when written in 1973.
Four stars

Leave a comment

Filed under Book Review

Book Review: Not All Superheroes Wear Capes, Danny Bent

This summer Danny Bent (author of this book) visited my firm to give a talk. He related some humorous tales from his life experience to bring home his positive attitude to life – he’s been voted one of the happiest 100 people in the UK, so he’s worth listening to. As part of his session, he orchestrated a group rock/paper/scissors challenge in which I reached the final (!) – my prize was a copy of this book.

The book is Danny’s story of how he came to co-organise One Run for Boston after the Boston marathon bombings in 2013. Not only did the relay run across America raise a lot of money, it provided a focus and support network for many of the victims.

Leave a comment

Filed under Book Review

C++ London Meetup: C++ 11 was only the Beginning

I was lucky to get a place at this month’s C++ London meet up, having a limited number of seats and being hosted by Smarkets at their offices in St Katherine’s Dock. Smarkets are an online betting exchange – and they’re currently hiring!

This evening was started by Alex Schmolck, presenting his work configuring the development and build systems for Smarkets. He’s experimented with Vagrant and Docker, but is now an advocate of Nix. He admits that Docker is initially more productive, but Nix has the edge for its efficiency and speed.

The main talk (see slides) was given by Mateusz Pusz, showing a series of examples to demonstrating how a body of code can evolve and improve significantly with the features introduced by C++11, C++14, C++17 and soon C++20.

For example, implementing functions with variable numbers of parameters – such as for populating a container of items for a testing library. With C++98, this might have led to many overloads with increasing numbers of arguments (but only ever handling up to some hand-coded limit). With C++11 onwards, you could use variadic templates, handling any number of parameters. And with C++17 onwards, you could use fold expressions to simplify the code further (no need to the ‘base class’ template overload).

Another interesting example was the evolution of Compile-Time Dispatch. Whereas even C++ 11requires hand-rolling overloads on a hierarchy of tag classes, post C++17, you can use constexpr to organise the code within a single method.

Leave a comment

Filed under C++, Meetup, Programming

Book Review: Origin, Dan Brown

Our charity bookshop had a rather nice hardback edition of this thriller from Dan Brown’s Robert Langdon/Tom Hanks series, and I’m glad I bought it.

Here, we see Langdon as a mentor to a brilliant student, Edmond Kirsch, who has become a successful entrepreneur in the world of technology. And whereas Langdon has sometimes lacked depth, in this book his relationship with the beautiful Ambra Vidal (fiancee to the Prince Regent of Spain) is more nuanced than I expected. The book demonstrates the spread of social media and its ability to rapidly set the agenda. Even better, there’s a science fiction element to it in the form of Winston, an AI agent built and employed by Kirsch as his assistant.

There are also some quintessential Dan Brown moments, such as the hidden symbology in the Fedex logo, the history of the ampersand and, my personal favourite, the answer to I + IX (it’s 10 or 12, depending on your point of view).

The premise of the book is that Kirsch has made a great discovery about the origin and future of the planet – how did life on Earth begin and what is its destiny?

Four stars

Leave a comment

Filed under Book Review

Tech Book: Data Science from Scratch, Joel Grus

This book is an excellent primer on data science. It builds up concepts from scratch with code examples in Python. Whilst it uses some well-known libraries for utilities, the code that builds on the core Data Science concepts is all included and explained in the book.

I particularly enjoyed the conversational, often humorous style of the book. He gives a short introduction to NoSQL databases, then concludes: “Tomorrow’s flavour of the day might not even exist now, so I can’t do much more than let you know that NoSQL is a thing. So now you know. It’s a thing”. The author doesn’t get too stuck in jargon either – one example is his definition of a greedy algorithm: “… at each step, it chooses the most immediately best option” – perfect.

Some of the main topics covered are:

  • Visualizing Data
  • Gradient Descent
  • Linear Regression
  • Logistic Regression
  • Neural Networks

Having covered the theory, the book extends to a few use cases – natural language processing, network analysis and collaborative filtering.

Four stars

Leave a comment

Filed under Python, Tech Book

Book Review: The Affair, Lee Child

I bought a nice soft-back edition of this Jack Reacher thriller some time ago, but it was well worth re-reading. There has long been a gap in Reacher’s history – how did he go from being an elite investigator in the Military Police to travelling around America as a loner? This book fills in the gap and is one of the best in the series.

Reacher is assigned to go to Carter Crossing to shadow the town’s police department in their investigation of a murder. Although he’s supposed to be incognito, the police chief, beautiful Elizabeth Deveraux, unmasks him immediately. No matter, because the two develop a very close relationship working on the investigation together. The author plants seeds of doubt about Deveraux – perhaps she has a hazy past, taking revenge on former boyfriends? Could this murder, and two others of similarly beautiful young women, be her revenge after she was dumped by Captain Reed Riley, son of a US Senator? A side plot is that, sometimes the cover-up is worse than the crime. In this case, Reacher wants to know why local militia were employed to defend the military base outside the boundary – leading to the senseless murder of a journalist and the brother of one of the murder/rape victims. He confronts Colonel Frazer of military liaison at his office in the Pentagon – did he authorise the cover-up to protect his investment made building relationships with the Senator?

I always enjoy the Reacher books where he teams up with locals to solve the case – and as a bonus, this book features Reacher’s favourite Sergeant, Frances Neagley.
Four stars

Leave a comment

Filed under Book Review