CPU Feature Detection
CPU Feature Detection
Join the DZone community and get the full member experience.Join For Free
Container Monitoring and Management eBook: Read about the new realities of containerization.
With so many great cross-platform libraries out there, there is hardly any need to reinvent the wheel. In many cases, it is even possible to extract a portion of a sophisticated multi-platform application code to be reused in a different application. In this example, a basic CPU detection class from Chromium C++ code is built into a simple command-line tool.
The challenge in such an extraction process is figuring out the dependencies. Chromium src/base directory contains a lot of useful basic classes for application development. They are however targeted primarily to be used when building Chromium alltogether. Often times, it means it is not easy to use only one class without pulling a series of other dependent classes. In the worse case, you will go down the rabbit hole.
For this exercise, we will be using the base::CPU class found in
base/cpu.h. As expected, this class depends on some other classes. Fortunately for us, it does not go that far. The dependency graph looks like the following:
Thus, what we need to do is to grab all those files from Chromium source code. So that you can follow along, I have prepared a Git repository bitbucket.org/ariya/cpu-detect. Once this
base::CPU class is ready, using it is trivial:
base::CPU cpu; std::cout < < "Vendor: " << cpu.vendor_name() << std::endl;
For the complete demo app, here is the full output when running on my Chromebook Pixel:
Since this is just an example, we omit a rather important thing. The class implementation actually needs to use StringPiece. In our flavor above,
string_piece.h is an empty file (to satify the include). We don’t need any code because StringPiece is only necessary for ARM architecture. If we stick with Unix on x86, then we can live with that dummy header file. Obviously, in real life and with other possible classes, you may not be that lucky.
Isn’t it true that we don’t code today what we can’t reuse tomorrow?
Published at DZone with permission of Ariya Hidayat , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.