Slashdot Mirror


Genetic Algorithms and Compiler Optimizations

mfago writes "Scott Robert Ladd has written an enlightening article and accompanying software package that utilizes genetic algorithms to optimize the optimization flags fed to a compiler. Those who have tried to squeeze the last drop of performance from a code know that it can be very difficult to determine the set of optimization flags beyond -O3 (with gcc for example) that yields the best performance. Lots of background links included in the article."

48 of 222 comments (clear)

  1. Beware the simple, elegant solution. by Thinkit3 · · Score: 3, Insightful

    Toss around terms like genetic algorithm and neural networks, and some are dazzled by the elegance and simplicity of it. Well, then there's reality, which is often neither elegant nor simple. In Go, there is a computer player that utilizes neural networks, yet it is near the middle of the pack.

    A good dose of skepticism should accompany any examination of the dazzingly elegant solution.

    --
    -Libertarian secular transhumanist
    1. Re:Beware the simple, elegant solution. by Anonymous Coward · · Score: 5, Insightful

      Yes, a good dose of skepticism should accompany such things... however, this particular example is one in which the search-space is finite, and you're using a genetic algorithm to cleverly navigate this space.

      Neural networks are good when there is a massive amount of unknowns to deal with, and you're better off handling any patterns you can detect, but this is just a simple case of using a new(-ish) method to compare runs with (nearly?) all parameters. Nothing to be skeptical about, really.

    2. Re:Beware the simple, elegant solution. by tessaiga · · Score: 4, Funny
      In Go, there is a computer player that utilizes neural networks, yet it is near the middle of the pack.

      Wait, I'm confused; I thought on Slashdot we're supposed to wait for someone to mention Chess before we bring up Go?

      --
      The bold print giveth, and the fine print taketh away ...
    3. Re:Beware the simple, elegant solution. by koekepeer · · Score: 4, Funny

      anyways think about the overkill of developing such an elegant solution for such a minor problem. i mean those few percentages of performance enhancement...

      anyway, i think it *is* really cool this guy finds it interesting to tackle this 'problem' with a genetic algorithm. why not try some bayesian networks next? support vector machines? improbability drives...

      ooops, i'm getting carried away. sorry 'bout that. /me bows in admiration

      (not intended as flamebait but mod me to hell anyway *evil grin*)

    4. Re:Beware the simple, elegant solution. by zanerock · · Score: 4, Funny

      Neural networks != genetic algorithms

      Slow Go player != inelegant solution

      I was going to dissagree with you, but I'm not even sure what your arguments are. Do you have any reason to believe that the solution for the problem discussed in the article is inelegant or innefficient, or did you just get a bad grade in your AI class?

    5. Re:Beware the simple, elegant solution. by pnatural · · Score: 3, Interesting

      Because you have a single data point from a related problem domain (that does not even use the same solution!) and the single data point does not perform well, the concepts presented in this article are what? Flawed?

      I suspect you either do not understand genetic algorithms, or that you do not have experience in a problem domain where GA could have been successfully used.

      Just because you don't understand GA doesn't mean that GA isn't applicable to this problem. I recently had a problem to solve similar to the problem outlined in the article (optimizing results with N variables, where N > 5) and the GA solution beat the pants off the brute-force solution.

      Note that I'm actually not saying that GA is a panacea; rather, I'm saying that for some problem domains, like the one in the article, it makes a whole lot of sense.

    6. Re:Beware the simple, elegant solution. by mfago · · Score: 4, Interesting

      anyways think about the overkill of developing such an elegant solution for such a minor problem. i mean those few percentages of performance enhancement...

      I'm sure some people would love a few percent improvement in their SPEC results...

      Personally, I have an algorithm that I'm running hundreds of millions of times as part of a larger calculation for my PhD research. I'd love a "few percent" improvement simply by changing the compiler flags.

      Acovea is curently a research tool in its own right, and not quite ready for application to general problems. Some issues that require modest effort to resolve:

      1) Code currently is pentium3/4 centric
      2) Optimizes flags for gcc 3.4 or intel's compiler
      3) Cannot easily handle code residing in more than one file.

    7. Re:Beware the simple, elegant solution. by Tet · · Score: 2, Funny
      In Go, there is a computer player that utilizes neural networks, yet it is near the middle of the pack.

      All the top of the pack human players use neural networks. Your point?

      --
      "The invisible and the non-existent look very much alike." -- Delos B. McKown
    8. Re:Beware the simple, elegant solution. by JaredOfEuropa · · Score: 3, Informative

      Neural networks are well-suited for tweaking the (possibly numerous) parameters of an established algorithm. It's good for finding good local maxima on n-parameter functions. Another technique for this is simulated annealing.

      It's the cleverness of the algorithm that makes a computerised Go player good. Using a simple stinky algorithm and tweaking its parameters isn't going to turn a mediocre Go player program into a great one.

      As always, you pick the solution that fits the problem.

      --
      If construction was anything like programming, an incorrectly fitted lock would bring down the entire building...
    9. Re:Beware the simple, elegant solution. by Dachannien · · Score: 4, Interesting

      What we should be most skeptical about is that Mr. Ladd wanted to study the effects of using a GA on optimization, yet he neglected to run a control sample involving random perturbation of options from the start case (-O1 or -O3), without selection.

      If, as I suspect, the search space is disorderly, then random perturbation should, among the same number of test compilations, be able to find a solution comparable to that which his GA finds.

    10. Re:Beware the simple, elegant solution. by vv2 · · Score: 2, Insightful

      Alternatively:- Add up the number of hours spent running optimisations on compiler flags, deduct actual time savings, times hourly rate and then see if it would be cheaper to add (scrounge) some more processors....

    11. Re:Beware the simple, elegant solution. by Hard_Code · · Score: 2, Insightful

      Pretty attractive if the first best solution takes longer than the age of the universe to compute, I'd say.

      --

      It's 10 PM. Do you know if you're un-American?
  2. Isn't this the Windows technique? by Anonymous Coward · · Score: 4, Funny

    That is, fiddle with settings at random until it's acceptable?

    1. Re:Isn't this the Windows technique? by LoztInSpace · · Score: 2, Funny

      I think by the time it emerged from marketing it would be a "stochastic process".

  3. I did for this for my Ph.D. defense by Anonymous Coward · · Score: 4, Interesting

    It turns out that hand tuning will ALWAYS get you the best optimizations, but human nature dictates that a certain portion of optimizations will never be found. Genetic algorithms will find some of these optimizations in a reasonable time, but not all. So the bottom line is, no code can ever be 100% optimized, unless it is compiled for weeks.

  4. cool application for GA by millette · · Score: 4, Interesting

    This is a very neat application of genetic algoriths! Haven't seen something so interesting since this Tron cycle game.

  5. Skepticism by wdavies · · Score: 5, Interesting

    It actually seems like a good idea.Some problems I can imagine are optimization flags may have non speed related side-effects?

    However, this seems like a great candidate for GA's - a fitness function (ie speed of execution), and a nice binary vector of atributes (flags).

    Interesting that the gains aren't that great it would seem to sugges that the flags don't do much :) or maybe the base-line is already close to optimal, and so it isnt a hard problem?

    But Kudos nevertheless. No expert in the GA field, so its possible someones tackled this before, but if they haven't, extra Kudos.

    Winton

  6. fragile GA, and what this is and isn't by kisrael · · Score: 5, Informative

    An important thing to note is that this isn't coming up with new optimizations, but rather finding the optimal mix of pre-existing gcc optimizations.

    It's an important distinction. When you're trying to do breed some really new system using Genetic Algorithms, it's possible to get some very fragile results, i.e. systems that do the job incredibly efficiently, but only under certain conditions...

    For instance, I remember reading some folks were trying to "breed" a circuit using Genetic Algorithm like techniques that created a "pulser" using as few gates as possible. They got something that used like one tenth the number of logic gates of the previous low record...but didn't work when they moved the setup away from their desktop PCs. Turned out what they "discovered" was a sensitive RF receiver that picked up (I think) something like the normal 120V cycling, and utilized. Similarly, a lot of the bred ciruits are extremely sensitive to temperature and other conditions.

    So breeding for efficiency can be a bit dangerous, you get things that rely on odd side-effects and environmental states. Though I think the method the article describes isn't much more dangerous than normal optimization selection, though admittedly more likely to stumble over some unusual flag combination that might break under certain circumstances.

    In short, *if* GA is ever going to let software development become more like gardening than engineering, (something I've herd as a goal) we're going to have to find ways to apply very general evolutionary pressures, complex test environments.

    --
    SO YOU'RE GOING TO DIE: The Comic for Dealing with Death
    1. Re:fragile GA, and what this is and isn't by elmartinos · · Score: 3, Informative
      When you're trying to do breed some really new system using Genetic Algorithms, it's possible to get some very fragile results, i.e. systems that do the job incredibly efficiently, but only under certain conditions...
      This is not a problem of the Genetic Algorithm in general, this is the problem of the fitness function: The GA always tries to produce something wich gets the best out of the fitness function (e.g, a pulser with as few gates as possible). If the fitness function also uses the stability of the result in its calculations, (which it should!), the GA will try to create very stable solutions.
  7. ... :P by rylin · · Score: 2, Funny

    Sadly, these genetic algorithms only work for blue-eyed developers

  8. Re:I have a better idea by IWannaBeAnAC · · Score: 2, Informative
    Because assembly language is fragile and not portable.

    A scheme for automating optimization choices is not fragile (when the code changes, just re-run the optimizer) and portable (when compiling on another machine, just re-run the optimizer). Beats assembly hands down.

  9. Compiler optimisations don't win you much ... by MrDelSarto · · Score: 3, Informative
    Todd Proebsting has a "law" like Moore's law ... from his webpage
    Moore's Law" asserts that advances in hardware double computing power every 18 months. I (immodestly) assert "Proebsting's Law", which says that advances in compiler optimizations double computing power every 18 years.

    There is more information on his webpage. It's not strictly true -- compilers have moving targets (different architectures and hardware optimisations over time, greater complexity in languages, etc etc), and for important things like scientific applications compilers can really optimise code; but in general R&D towards compiler development seems to be sorely lacking compared to other areas.

    I work on IA64, which is fundamentally designed to take advantage of smarter compilers. While there are some interesting projects (ORC for example) nothing is really close to ready to take over gcc/intel compiler. We really want something that compiles once, can profile code execution and then recompile to optimise based on the execution profile; something along the lines of what this article talks about but built right into the compiler.
  10. Why use a GA? by eclarkso · · Score: 4, Interesting
    In general, the literature suggests that GAs tend to be a kind of 'jack of all trades, master of none' type approach. See, e.g., Russell & Norvig's AI: A Modern Approach textbook.

    As such, is there any justification for using a GA to do this rather than, say, simulated annealing? I'd would be interested to see a comparison of the two approaches. Especially in light of papers like this one.

  11. How bumpy is the problem? Do you need a GA? by Animats · · Score: 5, Insightful
    You could probably get equally good results with plain hill-climbing. Turn on all the optimizations. Then turn them off one at a time and see if things get better. Repeat until no improvement is observed.

    Any time you consider using a broad-front search algorithm like a GA, a neural net, or simulated annealing, try plain-hill climbing first. If you try any broad-front search, compare it with plain-hill climbing. Only if the space being searched is dominated by local maxima (but not too many of them) do the broad-front algorithms help. And they're always slower.

    If this guy had demonstrated that a GA did better than a plain hill-climber, he'd have an interesting result. But he hasn't demonstrated that.

    1. Re:How bumpy is the problem? Do you need a GA? by SmackCrackandPot · · Score: 3, Informative

      You could probably get equally good results with plain hill-climbing. Turn on all the optimizations. Then turn them off one at a time and see if things get better. Repeat until no improvement is observed.

      It is known that some optimisations can disable others. For example, "merge frequently called functions with parent" will penalise "store frequently used variables in registers" or "give priority to inner-most loop variables in registers". You could certainly build on the research in this article. What are the best types of optimisations for different types of algorithm (B-tree traversal, matrix-vector mathematics, text-editing). Does compiling different modules of an application provide improved performance over compiling all modules with the same set of flags?

    2. Re:How bumpy is the problem? Do you need a GA? by Animats · · Score: 2, Insightful
      Actually, I meant to say hill-climbing rather than gradient ascent. True gradient ascent implies you can evaluate the local gradient, i.e. you can compute the derivatives which represent the local slope direction. You can't do that for discrite problems like this one. Gradient ascent is more appropriate to problems expressed as differential equations. (Although, having struggled with nonlinear differential equation solving in high-dimensional spaces for several years, I can report that it's no panacea.)

      By "broad-front search" I mean one where you're searching the surface defined by the objective function from multiple starting points. GAs, neural nets, and simulated annealing all effectively do this. All three approaches are really special cases of a more general search operation. Because partisans of each approach use such different terminology, (much of it borrowed from biology) it's not obvious that this is the case.

  12. Shortcomings by hibiki_r · · Score: 5, Insightful

    Having worked on applying GAs to multi-objective optimization, I don't belive that this technique can be used effectively to optimize most programs.

    The main issue is to compare the individuals generated by the genetic algorithm. To do so, we need to both compile the program under the specified settings, and then to be able to benchmark its performance. In my current job, a full build of our main product takes over 12 hours on an 8 CPU machine. Using a pretty conservative estimate, 100 generations with 100 individuals each, we'd be talking about more than a year of CPU time for a single run of the algorithm!

    Even if we could ignore the amount of time required for compilation, we still have a second, more important flaw: Most programs out there are not really that easy to benchmark automatically. Database applications might need to go back to a known DB state to be able to run the benchmark faily. Also, server apps need to have the exact same load for every test if we want to be able to compare two executables fairly. This problem is increased when many compiler options will just create a 1% performance improvement or so. A poorly run system could lead the comparison function to just pick the wrong executable if the two executables didn't run in the exact same conditions.

    I see how using GE for this task has a high coolness factor, and how it might even be usable for applications that are by nature easier to benchmark, but don't expect this technique to be applicable to enterprise-sized server applications, or even most GUI based apps any time soon.

    1. Re:Shortcomings by pmz · · Score: 2, Funny

      12 hours on an 8 CPU

      100 million LOC, really crappy makefiles, or eight 60MHz CPUs?

    2. Re:Shortcomings by psavo · · Score: 2, Insightful

      a full build of our main product takes over 12 hours on an 8 CPU machine

      Err.. ever heard of rule that 5% of code does 99% percent of work?

      If your application does 'diverse' kind of things (you mention DB's), then most probably when optimizing one module, you're hurting others. The obvious solution is to optimize module by module. Starting from the most abysmally slow, your build environment.

      --
      fucktard is a tenderhearted description
    3. Re:Shortcomings by Anonymous Coward · · Score: 2, Interesting
      In my current job, a full build of our main product takes over 12 hours on an 8 CPU machine. Using a pretty conservative estimate, 100 generations with 100 individuals each, we'd be talking about more than a year of CPU time for a single run of the algorithm!

      True, but you can still get some improvement with a procedure like this:

      1. Profile the code
      2. Identify the bottleneck (probably less than 1% of your source, based on what you say)
      3. Apply the genetic algorithm to that 1%, and find the best optimization flags for it.
      4. Then try two combinations: (a) use those flags for it only and use your regular flags for everything else, (b) use those flags for your whole project. Pick the best combination.
      5. Repeat as necessary with other problem areas in the code, again as found by profiling.

      In fact, this might get you better results overall than running the genetic algorithm against the whole project. Sometimes the optimal thing is to have one set of optimizer flags for a certain chunk of code and then another set for another chunk.

      Having said all that, this article was mainly intended for research purposes. The goal seems to have been to find out more in general about which flags matter and how much than it was about producing a technique for everyday compiling.

  13. No, GAs make great sense... by cduffy · · Score: 3, Interesting

    ...because they were able to pick out combinations of optimizations that measuring each optimization individually wouldn't have discovered.

    Consider the case in huffbench when
    -fmove-all-movables, -freduce-all-givs and -ftracer were discovered to result in great improvements when used with the other GA-selected optimizations -- but not when applied directly to -O3.

    Sure, these situations may be specific to the test cases -- but that's not to say his software can't be used to evaluate real-world scenarios as well, such that companies doing a final release compile of their code let a GA churn for a few days to determine the best flags to use.

    That's a Good Thing, no?

  14. Fix the Compilers by Gothmolly · · Score: 2, Insightful

    The compiler ought to optimize this stuff anyway! How about "set suck=(yes|no)" and "prefer=(speed|size)" as options. Let the compiler and its designers come up with what is required to meet (or approach) a programmer's wishes.

    --
    I want to delete my account but Slashdot doesn't allow it.
  15. Anybody remember Green Hills C Compiler by BanjoBob · · Score: 2, Interesting

    The Green Hills C compiler had all kinds of optimization techniques but they also had a way to measure the assembler output. One method would eliminate all symbols and make huge code that ran inline. The code was fast but used up a lot of disk space. They had many optimization options and dozens of flags that could be set so that the compiler would actually give you what you wanted. Analyzing the assembly code was a great way to learn the ins and outs of their compiler.

    --
    Banjo - The more I know about Windoze, the more I love *nix
  16. Re:GAs wrong tool for the job by pimpinmonk · · Score: 2, Funny
    I am as big a fan of GAs as the next guy
    So, you mean you have little or no idea of what GA stands for, let alone what it means and what its applications in computer science are?

    Sorry, couldn't resist :-)
  17. Re:GAs wrong tool for the job by GlassHeart · · Score: 3, Insightful
    Why couldn't he just measure performance with and without each optimization and see which had the greatest improvement? Yes, this might not take into account interactions between different optimizations, but to the extent such interactions occur, it would probably be specific to his test cases anyway.

    That's exactly the point. The goal is not to find a set of gcc switches that will work best on any program on any supported platform. The goal is to find the set that works best with this particular input, without human guidance.

    10% or 20% improvements in compiler performance are of largely academic interest only these days most software's time is spent waiting on user input, disk IO, or network activity anyway?

    First of all, what if you can get the 10% or 20% basically for free? That is, simply run your compile for a few unattended days to get the optimization? What is not worth human tweaking time can easily be worth machine time. Gentoo, although I do not use it myself, appears to be a vibrant Linux distribution based exactly on this point.

    Secondly, most existing software are running on small CPUs all around you, not on your desktop. The constraints of memory usage and CPU power are still very real for them.

    Finally, consider also that more efficient software may result in more idle hardware and lower power consumption. Imagine if all PCs in the world can get by with 5% less electrical power.

  18. The Golden Rule of Optimization by rhysweatherley · · Score: 3, Insightful
    Never forget the Golden Rule of Optimization: a quicksort compiled with no optimization will invariably beat the pants off a bubblesort compiled with the best optimizer in the universe.

    Optimizers change the constants in the algorithm running time. They cannot change the algorithm's order.

    With the exception of high-performance computing, no one needs a super-optimizing compiler any more. Instead, they need to (re-)learn basic algorithm and data structure theory.

    1. Re:The Golden Rule of Optimization by hh10k · · Score: 2, Insightful

      Perhaps you should re-learn basic algorithm and data structure theory, because bubblesort can beat the pants off quicksort when the data set is small enough. Anyway, if you're going to implement quicksort, don't you want a 20-30% faster quicksort?

  19. Re:I have a better idea by pmz · · Score: 2, Interesting

    A scheme for automating optimization choices is not fragile...

    Perhaps, someone should consider a GA for autoconf...

  20. Other ideas by adjuster · · Score: 3, Interesting

    This gets me thinking about Nat Friedman's GNU-rope (Grope) project. I heard him talk at ALS back in '98 and then the project seemed to completely disappear. Searching on "gnu.rope" leads to a few mailing list postings asking "where'd it go", but no good information about the project.

    The basic idea was to reorder the functions in an executable so that locality of reference was maximized and cache hits were increased. The result is less paging and better performance and memory usage.

    The really interesting bit is that the optimization is based on the usage of the program being optimized-- that is to say that my Grope-optimized version of Mozilla might be different than yours based on my differences in usage (i.e. perhaps I browse with images turned off, etc).

    The tie-in to the article here is that Nat's system, Grope, used simulated annealing to traverse the n-dimensional space of potential function arrangements and profiled the memory paging of the application as a fitness function of the new arrangement. It's not a GA-- but it's functionally similar.

    So-- anybody know what happened to Grope? I'd imagine that a community would spring up around it fairly quickly given the relatively high number of "performance zealots" who are busy "tricking out" their Linux boxes by compiling everything from scratch (think Gentoo) optimized for their procesor. Now they can add the "spolier" or "racing stripe" of having exectuables specifically re-ordered for their personal usage patterns! *smirk*

    --
    The Attitude Adjuster, I hate me, you can too.
    1. Re:Other ideas by bloosqr · · Score: 3, Informative

      I think this is actually what most two pass compilers will do. The intel compilers have this option for instance. Basically you compile w/ profiling on and on the second pass it using the runtime profiling data to recompile source to a new object code. (btw the intel compilers are "free" for opensource/nonprofit use). W/ regards to using GA/SA as part of the optimization it would be (to be honest) a bit weird to have a nondeterministic compiler since in different runs you may end up w/ different optimizations.

      -bloo

  21. Reliability, and porting to Macintoshes... by billstewart · · Score: 4, Insightful
    Doing lots of Pentium-specific tweaks in your code may be zero or negative help when somebody wants to run it on a Macintosh....

    More importantly, tweaking code for heavy optimization is not usually a good job for humans. It's fine if you've got a piece of hardware that you have to tweak the last few percent performance out of for an application that will run for many CPU-years, but you're almost always much better off if you

    • Pick good algorithms
    • Leave bit-bashing loop-twiddly optimization tricks to the compiler, and
    • Put your human creativity skills to work on the next revision of your code, or on your next project if this one is done.
    --

    Bill Stewart
    New Fast-Compression-only CPR http://preview.tinyurl.com/dy575ks
  22. Atlas :: empirically optimized blas/lapack by bloosqr · · Score: 2, Informative
    There is a variation of this that is very clever that optimizes BLAS and LAPACKroutines "empirically" called ATLAS that has been around a while, originally (and perhaps still) a research project by err Clint Whaley from tennessee (BLAS/LAPACK are numerical routines that do a slew of thing people generally find useful linear algebra and vectors). These routines will often time sit "under" many mathematical packages like matlab/octave/maple/mathematica/scilab as well
    as make up the core of much custom scientific computing packages (or even libraries like the "Gnu Scientific Library")


    Basically the jist is atlas "empirically" (read: use an optimizer for instance like GA, though empirical may actually mean brute force in this case) to optimize various parameters that will affect things like optimize the routine for the cache size of the processor etc. The cool thing about this, is they can get w/in 10% of hand machine coded BLAS/LAPACK libraries w/out the pain!

  23. GA exploit environments' flaws by Hjallli · · Score: 3, Informative

    The "folks" you refer to is Professor Adrian Thompson of the University of Sussex. A paper describing his interesting experiment can be found here. It was actually a flawed FPGA chip he was programming.

    Another example of this tendency of Genetic Algorithms to make use of helpful "flaws" in their environments can be found in the works of Karl Sims. A round-off error in his physics model resulted in some weird locomotion by a branch of virtual creatures.

    You will find details of both examples in this entry on my Wetware blog.

  24. And your point? by devphil · · Score: 3, Insightful


    While I don't disagree with your observations, I'm confused as to what they have to do with Ladd's project and the results shown.

    Okay, find, I've written my decent quicksort. I know my basic algorithms and data structures. Now I would very much like to squeeze every last drop out of them. Here's a project that will tell me a good combination of options to use as a starting point. Don't tell me that I should just ignore all that and go re-re-re-learn basic algorithms. GCC is used by more than students.

    More than that, it will tell the GCC maintainers which options should be on by default which currently might not be, and vice versa.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
  25. Not the point by devphil · · Score: 2, Informative
    Having worked on applying GAs to multi-objective optimization, I don't belive that this technique can be used effectively to optimize most programs.

    Good, because that's not the original intent of the project. When he first contacted the GCC maintainers about the project which would later be called Acovea, the idea was to see which underlying -f/-m options shod be turned on by the -O? options by default. More and more projects using 3.2 and 3.3 were using "-Osomething -fno-something -msomething" so he took the 3.4 (in development) code to see what should additionally be turned on and what should be turned off instead.

    While you can use it to tune for particular programs, and particular patterns of use, it will mostly be useful to GCC itself.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
  26. Re:Code-generation bugs by RML · · Score: 2, Informative
    Of course, buggy code is more likely actually to fail under aggressive optimization. I've certainly had to maintain lots of buggy code, although of course I never write any of it myself. (Did you know that

    union { char c[8]; double d; } u;
    u.d = 1.0;
    char c = u.c[1];

    yields undefined results? The compiler is allowed (and under -O3, encouraged) to generate code that will erase your disk and impregnate your sister.)


    Sorry, you're wrong, for two reasons:
    - A char* can be used to point to anything.
    - You can write to one member of a union and read from another.

    Both of those are implementation-defined, not undefined. Undefined means the compiler can blow up your computer. Implementation-defined means that the compiler must do something consistent and documented.

    If, however, you had written
    double d = 1.0;
    int i = *(int *)&d;
    you would have been correct.
    --
    Human/Ranger/Zangband
  27. Simulated Annealing for Optimization by exp(pi*sqrt(163)) · · Score: 2, Interesting
    Years ago I wrote some code that could tell if a pair of instructions 'commuted' in the sense that they could be reordered without affecting the functionality. Eg. "mov eax,1" and "mov ebx,2" are likely to be swappable but "mov eax,2" and "add ebx,eax" almost certainly can't be. I then used simulated annealing to walk through the space of code segments equivalent under commutation in an attempt to find the reordering optimal for the CPU pipeline.

    In other words I randomly swapped pairs of instructions that could be swapped, if it saw an improvement it kept it and if it saw a degradation it rejected it with a probability depending on how bad it made things.

    After hours of running it would sometimes trim a clock cycle or two per loop off a short assembler routine.

    --
    Doesn't it make you feel good to know that our freedoms are protected by politicans, lawyers and journalists.
  28. Good solution to the wrong problem by WayneConrad · · Score: 2, Insightful

    There are domains where squeezing every last cycle out of the code matters. Many of us no longer work in those domains. Most of the code I've written in the last 4 years was developed and executed in an environment with essentially unlimited cycles, memory, and disk. The only exception was one project that got database bound, and compiler optimization won't help that.

    For programmers who are no longer resource limited, using a language that optimizes for the human rather than the computer is a good idea. A language with garbage collection, low syntactic sugar, functional constructs like closures, and no separate compile phase make for happy code and happy programmers.

    An interesting benefit of working in a humane language is that it can becomes easier to use a better algorithm. Many algorithms depend upon data structures that are difficult to implement in the land of DIY memory management, but a breeze in a more humane language. This can make a solution in the apparently unoptimal language outperform the solution in the optimal language. Of course, we *could* go faster using C or C++, but only if we have the extra time it takes to write the code.

    Don't optimize for the computer unless the computer is the critical constraint. And, even then, only optimize the part that is the actual constraint.

    Otherwise, optimize for the human. We're more important than the computer these days.