Transparent C++ Number/Int Wrapper

2019-08-01 16:17发布

I've made a class for working with bits for unsigned int(8, 16, 32...), and I've been trying to benchmark it compared to the bare bitwise operations but getting an accurate test of the speed of bitwise operations is complicated to say the least. The reason for the wrapper is that it is a lot less complicated to use.

Now, while this may be more academically useful than practically, I would like to know if it was possible to make a class wrapping around an int that is so transparent that it is like working with the int directly (with all possible operators) except with functions that let me manipulate it in certain ways, and if it is possible to be as fast (with a lot of inlining).

I'm okay with using any and all C++0x features to achieve this.

3条回答
2楼-- · 2019-08-01 16:32

You can setup a custom class and overload all the relevant operators (arithmetic operators, comparison operators, bitwise operators, conversion operators) and supply your own behaviour as needed.

As far as I know, it would indeed be possible to make it behave like an int in almost all respects.

An inlining compiler will presumably do a very good job at removing most of the overhead, but to find out how good the results are, you will need to try it out.

Such a type would have little use for benchmarking, though - I'd rather repeat the very same operations until the relative error in your measurements get smaller. It's more or less impossible to time the speed of a something like a single bitwise operation as it really boils down to one or two machine instructions.

查看更多
叛逆
3楼-- · 2019-08-01 16:34

Yes, it's possible; but I think you might find it easier in the long run to just write some templated inline functions that you can call with various int8/int16/etc arguments. That way you don't have to worry about how to handle passing objects of your class to functions that expect regular integers, and vice versa. (Not that that isn't doable as well, but it might keep things simpler to avoid that issue entirely)

查看更多
Fickle 薄情
4楼-- · 2019-08-01 16:37

Templates?

Also, what is the difficulty in profiling your operations? The usual way is to do the same operation X times and then get the average. If you're on an Intel CPU you can read the CPU's timers before and after each operation and then get the average it has some flaws but should be relatively ok for your purposes

http://en.wikipedia.org/wiki/Time_Stamp_Counter

Also, you can look at the asm the compiler generates when your class is used and see if there are any areas where you can refactor your code so that it can do a better job at optimisations.

查看更多
登录 后发表回答