3 ms·
3 is actually a quite valid point for embedded. Any swap actually will be expensive when it comes to keeping cache lines clean. The correct answer in that cas
by leif 16y ago
3 is actually a quite valid point for embedded. Any swap actually will be expensive when it comes to keeping cache lines clean. The correct answer in that case is just to not swap the variables, and instead swap their uses later on:
int x, y;
...
SWAP(x, y);
foo(x, y);
becomes
int x, y;
...
foo(y, x);
(naturally, this is why I still eagerly await the arrival of a C compiler that has macros with LISP power)
- pjscott 16y agoIn that case, you can get the right behavior by just swapping the variables using a temporary variable. If the compiler is decent, it'll automatically swap their uses later on. I don't know how every compiler works, but if you use Clang (or anything LLVM-based), it converts everything to Single Static Assignment (SSA) form: int x1 = 42, y1 = 666; ... int tmp = x1; x2 = y1; y2 = tmp; // SWAP(x, y) foo(x2, y2); In SSA form, the value of a variable does not change, so it ends up creating a bunch of "imaginary" variables to hold intermediate values. From there, it does optimizations, then figures out how best to allocate registers, and what needs to be stack-allocated.
- leif 16y agoCool, thanks. I know far too little about compiler optimizations, it's always nice to hear about them.
- ay 16y agoIt's already there: http://chaos-pp.cvs.sourceforge.net/chaos-pp/order-pp/example/bottles.c?revision=1.10&view=markup http://chaos-pp.cvs.sourceforge.net/chaos-pp/order-pp/exampl... But I do not envy the poor soul who would have to maintain all this cleverness.