Write A Function To Determine If A Number Is A Power Of 2 - <AUTHOR> http://www.skorks.com/2010/10/write-a-function-to-determine-if-a-number-is-a-power-of-2/ <comment><USER2> 1990: a junior programmer who doesn't know any better:

      IF NOT(MOD(X,2)) THEN...

2000: a senior programmer, using OP's slick bit flipping approach:

      def power_of_2?(number)
       number != 0 && number & (number - 1) == 0
      end

2010: either a master or a lazy programmer, having pity on whoever has to maintain it:

      if !(mod(x,2)) then ...

Now that clock speeds are so much faster, can we all just go back to being lazy and focus on the real problem at hand?

[EDIT: Oops, I confused "power of 2" with "divisible by 2", rendering my entire comment stupid and pointless. But I won't delete it because so much is hanging below it already. This is a perfect example of what we hackers can never allow ourselves to do: wave our hands at the trees because we're so busy looking at the forest. I promise I won't do this again, at least until tomorrow. Now I'm going to close my browser and get back to work :-) ]

<comment><USER3> mod(x,2) will tell you that it's even, not that it's a power of two.

<comment><USER4> I think his first example was a recursive function like:

      if !(mod(x,2) {
       if (x == 1) return true  else return false;
      }else return is_power_of_2(x/2);

or

      if !(mod(x,2) {
       if (x == 1) return true;
       if ((x > 1) || (x == 0)) return false;
       return is_power_of_2(x * 2);
      }else if (x > 2) return is_power_of_2(x/2) else return false;

PS: 2^0 = 1 and 2^-1 so you could have 3 versions of this fuction.

</comment></comment></comment><comment><USER5> For almost all typical programming jobs out there, isn't asking a question such as this like hiring someone to flip burgers and expecting them to demonstrate how to butcher a cow during the interview?

<comment><USER3> Expecting the bit arithmetic would be for some positions. But asking a programmer to design and implement an _extremely_ basic algorithm doesn't seem unreasonable to me.

<comment><USER5> I guess I was focusing on the bit-level answers since that's what the article and most of the comments seem to value the highest.

You're right, though, the original question itself is not so much of a problem, I suppose. What bothered me is the subtext that, unless you get down to the bit level with the minimum possible number of CPU instructions in the result and do the compiler's job yourself, you're not a "real programmer" or something.

<comment><USER6> I disagree. A "real programmer" should know something about how the computer works, and should not revere anything below his level as "magic" or be afraid of it, even if he/she will never need to deal with it. Understanding that integers are stored as binary bitstrings, and what this means, is the most basic level of competency in this area.

</comment></comment></comment></comment><comment><USER7> Great write-up on the thought process of solving this problem.

Bit tricks like these are one of the reasons I love working on a few microcontroller projects each year. It's too easy to get lazy and sloppy when you have multiple GB of RAM and multi-GHz CPUs at your disposal. Coding for a microcontroller with 2KB of flash and 128 bytes of RAM forces you to carefully evaluate the architecture of your code and find the most efficient way of solving your problems. From my experience, that tight-code thought process tends to stick with me when I return to bigger projects in higher-level languages.

</comment><comment><USER8> Every positive number is a power of 2. Yes, I know, but there is no mention of "integer". Btw, I would just check if log2(x) is an integer.

<comment><USER6> positive, real

<comment><USER8> Right, if you are going to be pedantic, you should go all the way to the end.

</comment></comment></comment><comment><USER9> For those interested in these types of problems and solutions, check out "Hacker's delight", it's a pretty amazing read:

<http://www.amazon.com/dp/0201914654/>

</comment><comment><USER10> For more of this sort of thing:

[http://www.amazon.com/Hackers-Delight-Henry-S- Warren/dp/0201...](http://www.amazon.com/Hackers-Delight-Henry-S- Warren/dp/0201914654/ref=sr_1_1?ie=UTF8&s=books&qid=1287508570&sr=8-1)

which should be on every serious programmers bookshelf. Take a look, also, at the wonderful MIT HackMem report. Its Wikipedia entry, <http://en.wikipedia.org/wiki/HAKMEM>, has pointers to online versions. The venerable PDP-10's influence shows, but there's lots of cool stuff there.

Knuth's Art of Computer Programming,read closely, occasionally divulges clever hacks, particularly in the exercises.

</comment><comment><USER11> Using gcc compiler intrinsics (which should compile to a single assembly instruction where possible):

      bool isPowerOf2(unsigned int n) {
        return __builtin_popcount(n) == 1;
      }

</comment><comment><USER12> Correct me if I'm wrong, but I don't believe the bit twiddling trick would work on floating point representations, would it?

<comment><USER13> With floating point, the first 9 bits are sign and exponent. You could thus check with:

        int ispoweroftwo(float x) {
            return !(*(int*)(&x) << 9);
        }

This only works for exact powers of two, though. It's possible to get something that's really close that will fail this.

</comment></comment><comment><USER14> This reminds me of an assignment we had in one of my CpE classes. We had to implement a whole bunch of interesting operations using a limited set of operators and in as few operations as possible. Favorites:

Absolute value of a signed it:

a= x >> 32

return (a + x)^a

Swap values of two ints without a temporary int:

a^=b

b^=a

a^=b

! operator (boolean not) without any boolean operators:

int a = x | (~x +1);

int b = a >> 31;

return b + 1;

There were a ton of interesting problems. Made for a great assignment.

<comment><USER15> _Absolute value of a signed it:_

        a= x >> 32
        return (a + x)^a

Careful; right-shifting by >= the size of the type is an undefined operation, and might not do what you expect in all cases. (For instance, it might do nothing at all on x86, as integer shifts/rotations in ia32 are all performed modulo 32.)

</comment></comment><comment><USER16> My only problem is the seven lines of test cases at the bottom.

I'm not against testing, but I find many people using testing that excessively, start using it as an excuse not to bother thinking about if their solutions are correct or not.

<comment><USER17> If you're writing seven lines of test cases and just running your solution through the interpreter/compiler without thinking, sure. If you're writing seven lines of test cases and glancing back over to them as you write the solution it's a tool to help you think about whether your solutions are correct or not. In an interview/whiteboard environment you're going to be closer to the latter, if only because you're not going to have an interpreter at hand.

</comment></comment><comment><USER18> why not use logs? in python:

      >>> from math import log
      >>> def isPower2(val): return False if (val == 0) else  (log(val) / log(2)).is_integer()
      ...
      >>> isPower2(0)
      False
      >>> isPower2(1)
      True
      >>> isPower2(2)
      True
      >>> isPower2(3)
      False
      >>> isPower2(4)
      True
      >>> isPower2(1024)
      True
      >>> isPower2(1025)
      False

<comment><USER14> I'm guessing & and - are much quicker than log. & is a single instruction, - is a single instruction. The == are single compare instructions. I'm not sure about the && , but otherwise this is simple enough to write in ~20 lines of assembly.

<comment><USER19> Fast integer log2():

      static unsigned int mylog2 (unsigned int val) {
          unsigned int ret = -1;
          while (val != 0) {
              val >>= 1;
              ret++;
          }
          return ret;
      }

Faster log2() (thanks to [1]):

      static const char LogTable256[256] =
      {
      #define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
          -1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
          LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6),
          LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7)
      };

      unsigned int v; // 32-bit word to find the log of
      unsigned r;     // r will be lg(v)
      register unsigned int t, tt; // temporaries
      if (tt = v >> 16)
      {
        r = (t = tt >> 8) ? 24 + LogTable256[t] : 16 +  LogTable256[tt];
      }
      else
      {
          r = (t = v >> 8) ? 8 + LogTable256[t] : LogTable256[v];
      }

Fastest log2() on x86:

      #include <stdint.h>
      static inline uint32_t log2(const uint32_t x) {
        uint32_t y;
        asm ( "\tbsr %1, %0\n"
            : "=r"(y)
            : "r" (x)
        );
        return y;
      }

On ARM, one can replace bsr with clz.

You can figure out that a logarithm in base 2 is easy to compute in base 2 arithmetic (sounds kinda obvious, too); it's the position of the most significant bit set.

Now someone needs to come and point out that BSR has a latency 16 times that of AND, and 4 times the throughput. Touche, gentlemen.

[1] [http://graphics.stanford.edu/~seander/bithacks.html#IntegerL...](http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious)

</comment></comment></comment><comment><USER10> No one seems to have restricted their solution to n < N even though they make implict assumptions about the size of n when proposing a solution.

</comment><comment><USER20> I picked up this trick from reading the scrypt source code. A few months later I was asked it in a job interview. Thanks, Colin :-)

<comment><USER21> I can't claim much credit here -- that trick is older than I am. :-)

</comment></comment><comment><USER22> Do people really expect interviewees to write tests during interviews? I've never seen that from either side of interviewing.

<comment><USER6> Yes. Microsoft asked me to verbally test my code (come up with a few examples and walk through the code), and Google asked me to describe a range of test cases to start with, and to decide if my code passed them.

They want to know that you know what sorts of inputs to start testing on (empty input, if that's valid, each obvious corner case (can you find all the corner cases quickly? This is a good skill to have), etc.) and that you can do this mentally a little before you compile and run the tests.

<comment><USER22> Oh yeah, I've been asked to describe how I would verify my code was correct including edge cases, but I've never seen people actually write test code.

<comment><USER6> Yeah, that I think would be toeing the envelope.

</comment></comment></comment></comment><comment><USER23> In the final version of x&(x-1)==0, one part was overlooked- negative numbers :)

Take the modulus and do the bitwise check!

<comment><USER3> Negative numbers cannot be powers of two.

<comment><USER23> That's definitely true- but say you want to check for (+/-2)^n, then you would have to deal with negative numbers.

If you go by the Two's complement representation, then for a negative number say (-8), because of sign extention, a check for x&(x-1) would fail.

</comment></comment></comment><comment><USER6> Did anyone else think "don't you just check if it's on the positive real axis?"

<comment><USER24> Well... we can just check if it's nonzero. They didn't say _real_ power of 2. :-)

<comment><USER6> silly me

</comment></comment></comment><comment><USER25>
      bool powerOf2(int a){
         return !(a & (a-1));
      }

</comment><comment><USER26> how many points do you get for simply parsing the output of bash's _factor_ function?</comment>


Angels to entrepreneurs: You don't want our money - <AUTHOR> http://atlanta.bizjournals.com/atlanta/stories/2009/02/09/daily68.html?ana=e_du_pap

<comment><USER2> I think this is actually pretty solid advice. If you have to take on external capital do it only when your own resources are absolutely exhausted. If you have a fancy car, a house without a mortgage and you're going out there to get a couple of grand of seed capital in order to launch your startup you are doing something badly wrong.

Assuming, of course that you really believe in your new venture it is much smarter to:

\- liquidate any assets that you have that you can easily get some money for

\- borrow from your bank, they take interest, not equity

\- use your savings if you have any

If the above is not an option and you are starting your startup with $0 in your pockets and out of necessity rather than because you really have a working idea then I would suggest to get a job, work for a bit, save a bit and try to launch your startup on the side.

Once it's a going concern, you have your idea ready to launch of you've already launched and you can present some initial growth figures then you're ready to take on external investors.</comment>


Is Carrot Dating, the Bribe-Based Dating App, Really So Bad? - <AUTHOR> http://motherboard.vice.com/blog/is-carrot-dating-the-bribe-based-dating-app-really-so-bad

<comment><USER2> What a curious example of symbiosis. Guy trolls journalists with a deliberately controversial app, knowing he can count on their indignation to make them write about how awful it is and thus send him lots of traffic. And then an "edgy" publication passes on the troll directly to us by defending it, thereby getting attention for themselves as well.

</comment><comment><USER3> I've never understood why prostitution is still illegal. A mutually acceptable transaction between two adults shouldn't be regulated.

<comment><USER4> I am willing to bet that in the vast majority of cases (in the US), it is exploitative to women. Women who stand on street corners and sell themselves are usually not doing it because they think of themselves as liberated. They do it because they need to make ends meet, and because if they don't, they will get in trouble with their boss. When people on HN think about prostitution, they think of escorts, not $50 hookers (or women who don't even get paid).

<comment><USER5> That's why in many of the countries where prostitution is legal, pimping is still illegal.

On the other hand, the results of at least one study suggest that prostitutes who work with pimps earn more, work less hours and have lower rates of injury.

Extreme Prelimary Study here: [http://economics.uchicago.edu/pdf/Prostitution%205.pdf](http://economics.uchicago.edu/pdf/Prostitution%205.pdf)

Note, for better or for worse, one of the authors is associated with "freakaonimcs."

</comment></comment></comment><comment><AUTHOR> The crudeness of the intro video on the site and the PR material aside (quite successful in its sensationalistic goal) it's really interesting to read people's reactions to them. The idea is in fact prevalent in the animal kingdom, e.g. male spiders routinely give presents to females to mate with them ([http://news.nationalgeographic.com/news/2005/02/0214_050214_...](http://news.nationalgeographic.com/news/2005/02/0214_050214_valentines.html)). The notion, of course, is that us, being humans, are way above these animalistic methods. Are we? As the Merovingian puts it: "And this is the nature of the universe. We struggle against it. We fight to deny it, but it is of course pretense. It is a lie. Beneath our poised appearance, the truth is we are completely... out of control".

<comment><USER6> It's kind of hilarious to see a Merovingian quote here, but I agree that the ridiculous "we're people, not animals" argument can't be disparaged enough. A limited but very significant example of this is the fact that the vast majority of money made on mobile apps and games depends on behavioral conditioning. You know... ring the bell, dog salivates? We've been doing this for decades -- just look at my Final Fantasy collection -- but only now is it really juicing us for cash at optimal levels. And it's not because we're Impressively Sophisticated.

</comment></comment><comment><USER7> I don't understand what's wrong with this. Of course it is crude and the creator comments are offensive. But the creator does not sugar-coat the product in any way. He clearly says its a dating app to bribe woman. He's calling a spade, a spade. And I am sure there will be enough men who want to use this to get dates. If you don't like the idea, don't use it. Why bash the creator. Let the idea die because of lack of attention.

</comment><comment><USER8> I find it funny that (as I expect) there would be much less buzz if they have used "gift" instead of "bribe". I'm really curious what the final reaction of the potential customers (of both sexes) will be. My guess is the majority of both man & women will reject such unromantic way to find the "other half". Of course if this app is about long-term relationships at all.

</comment><comment><USER9> Even if it is prostitution what is wrong with it ?

</comment><comment><USER10> Pretty funny, I'm not a feminist or a conservative so I don't think there's anything wrong with this, although it looks like a recipe for getting ripped off.

<comment><USER11> Without invoking any feminism or conservatism, I think it's fair to say that encouraging personal relationships to involve bribery (even if the use of the word is in a tongue-in-cheek manner) devalues them and pushes them towards being transactions. Call me old-school, but I do not want my personal, friend, or business relationships to be transactions.

My opinion would be that this seems like a very slick way (by both the app, and it's colourful carefree branding, and the article, written carefully to benefit from controversy and deflect criticism) to gloss over a fundamentally ugly idea.

</comment></comment><comment><USER5> Looking at the list of incentives, I see that it starts off with paying for a meal. I've always thought that the societal expectation that (1) men should ask women out on a date and (2) because they made the invitation they are responsible for picking up the bill is just a form of low-rent prostitution.

I've only dated women who were willing to go dutch and I'm glad that society has been moving away from that norm because it belittles women, particularly the ones who don't recognize it as such, because it says you are valued simply for being female (like 50% of the population) rather than valued for what makes you uniquely you.</comment>


Ask HN: Is Bay Area / SF good place for a 40 year old Programmer? - <AUTHOR> I am a 40 year old iOS programmer and work/life balance is important to me. I am looking for my next gig. I live in Los Angeles and thinking of moving out of the city to start something new.
Is Bay Area a good place to move at this age ? <comment><USER2> Depends on your depth. I'm 38, and I have opportunities thrown at me every day, based on a resume with work experience going back to '99, so my age is easy to tell (I'd actually assume that I was 40 from my resume).

There's some ageism, but if you're current on technologies and are charismatic during a phone interview you can make it happen.

</comment><comment><USER3> No (sadly). There are lots of other cities with cultures that do value your experience, though.</comment>


One-atom-thin 'silicene' silicon transistors invented - <AUTHOR> http://www.kurzweilai.net/one-atom-thin-silicene-silicon-transistors-invented

<comment><USER2> Last year when I was looking into silicene it was all very controversial and nobody seemed to have given all the necessary evidence to prove they'd made it (i.e. honeycomb lattice with the right atomic spacing AND dirac cones in the bandstucture).

Now I guess it's not only accepted but there are already devices? That's some rapid progress.

</comment><comment><USER3> Can someone knowledgeable about this field comment on how big this invention is?

<comment><USER4> We've known about silicene and germanene for a while, the question of their stability free standing is still open. But because their application primarily lay in electronics the goal is to grow a silicene or germanene in place, on top of some inductor and use it as is. Its hard though, you need just the right surface with just the right AVD settings. Basically you do a few thousand simulations to figure out what _might_ work, then you lock a grad student in a lab and have them try to grow it.

We knew it would likely be possible to grow, but how easily and what final properties it would have (due to interactions with the surface it is grown on) weren't entirely known. Also keep in mind this is one of a dozen different possible technologies for building future devices with.

</comment></comment><comment><USER5> One step closer to the Singularity.</comment>


Procedurally Generating Islands (2017) - <AUTHOR> https://plaxdev.wordpress.com/2017/05/04/procedurally-generating-islands/ <comment><USER2> Wow, this whole website is great, thanks for posting this! The frontpage post is currently "Naive City Generation" \- [https://plaxdev.wordpress.com/2017/09/11/naive-city- generati...](https://plaxdev.wordpress.com/2017/09/11/naive-city-generation/)

Reminds me of a great stack exchange post, "What are some ideal algorithms for Rogue-like 2D dungeon generation?", although the popular algorithms for dungeons and the like always seem less seed generated, for some reason.

[https://gamedev.stackexchange.com/questions/2663/what-are- so...](https://gamedev.stackexchange.com/questions/2663/what-are-some-ideal- algorithms-for-rogue-like-2d-dungeon-generation)

<comment><USER3> IIRC it is so that you do not need to save the entire game world with a save game. You can just use the seed to recreate the world.

</comment></comment><comment><USER4> I dabbled with terrain generation many years ago. Did the think of using noise, I used midpoint sub-division. Fun times.

</comment><comment><USER5> Is anyone aware of a generator that uses simulation of geological processes? Volcanic processes, raising/sinking plates, followed by erosion, creating rivers, lakes, elevation/temperature based vegetation?

<comment><AUTHOR> I'm not, although I'm sure there's something out there like that. Especially in the river generation domain with erosion models applied.

It'd certainly be an interesting project to build.

</comment></comment><comment><USER6> Perlin noise is my favourite noise. It's quite awesome what you can achieve with a couple octaves of it.</comment>


Ask HN: Recommended VPS providers - <AUTHOR>

Hey guys, I currently have a 2GB server with slicehost which ends up io bound a lot of the time (big db).  I'm thinking about getting a server with more ram - 4, 8, or 16GB depending on cost. Do you know of any good providers out there who are low cost - or who provide higher ram packages with lower bandwidth and hard disk offerings?<p>I'm looking for cheap as I'm completely bootstrapping and doubt I'll be bringing in any revenue in the next few months.  Any suggestions appreciated. <comment><USER2> I use SilverRack (<http://silverrack.com/>) and find it very cost-effective.

They have some discount codes you can use, and if you ask them they'll probably give you one.

<comment><AUTHOR> Thanks for commenting, but their largest VPS only has 1GB of ram. That's half what I have now.</comment></comment>


Synchronized Cycling - Like Synchronized Swimming, But Way More Amazing - <AUTHOR> http://missioncycling.org/wp/2009/08/18/synchronicity/

<comment><AUTHOR> The part where they cycled backwards while standing on top of each other was pure amazing. made me rethink what a bicycle is!

</comment><comment><USER2> Amazing stuff, I probably would have seen it on reddit if I was still reading it.</comment>


Non-profit produced MDMA 'ecstasy' and psychedelics - <AUTHOR> https://www.indiegogo.com/projects/non-profit-produced-mdma-ecstasy-psychedelics--2 <comment><USER2> This is easy to get behind. Although I have doubts of ever seeing these products on store shelves in the US, one of the things that have kept my personal drug experimentation extremely low is fear of product purity and lack of quality control.

It's easy to show how terrible the War on Drugs has been. I'm still against legalizing the worst of drugs like meth and heroin. But marijuana and LSD, other plant-based psychedelics, I'm mostly for.

Keeping drugs under ground and in the shadows funds Mexican drug cartels and puts the lives of millions at risk, while causing medical patients continuous, unnecessary suffering. Legalization and good QC is the best thing we could hope for.

<comment><USER3> It's a slippery slope to pick one drug as OK and another as not. Putting substances into your own body should not be illegal, regardless of the substance. We would do a lot better if we focused on education, addiction, and rehab than focusing on prohibition.

<comment><USER4> > Putting substances into your own body should not be illegal

Why is this so? By axiom?

Any parent will forcibly forbid her child to put any substance in his body. We make things illegal exactly because we recognize that a sufficiently large portion of the population is unable to handle a certain freedom. Now what exactly made you conclude that a sufficiently large percentage of the population can handle their use of drugs?

<comment><USER5> Because arguably, the reason you shouldn't put these substances in your body is because doing so can be unhealthy. Criminal charges and prison are definitely unhealthy.

Making a person's diet a matter of law just goes against the values of many people. I'm well aware of the fact that some compounds lend themselves to addiction/habituation but so do many legal ones. You don't see people throwing winos and pack-a-day smokers in prison unless they otherwise break the law in a way that infringes the rights of someone else.

Likewise, if someone fails to use intoxicants or other recreational drugs responsibly and develops a debilitating habit, it makes more sense to do as we do for people who want to quit drinking or smoking, not as we do for people who rape and murder.

<comment><USER4> > Criminal charges and prison are definitely unhealthy.

Making someting illegal does not mean you have to put people in prison. You do understand that we can forbid a drug and try to stop the sale of drugs, and still provide support for people who develop drug habits?

Funny that you mention cigarettes. I'm quite sure that cigarettes will be made illegal at some point in the future.

<comment><USER6> Actually, it basically does mean you have to put people in prison. What else are you going to due if its illegal? Fine them? Great, they'll never pay the fine, do more drugs. Now what? Fine them some more? Okay...it only goes on so long until they go to jail.

Any punishment oriented consequences are simply going to either be too harsh, or too lenient.

</comment></comment></comment></comment></comment></comment><comment><USER7> The folks involved did an AMA recently: [http://www.reddit.com/r/science/comments/2ywf4a/science_ama_...](http://www.reddit.com/r/science/comments/2ywf4a/science_ama_series_we_are_teri_krebs_p%C3%A5l%C3%B8rjan/)

</comment><comment><USER8> They want people to give them $1M for empty boxes from the future? Are they on drugs?

It might well be a good idea to study the therapeutic applications of these compounds more, or to change the laws. But the bottlenecks are in laws and in actually establishing the medical utility, not in synthesis. If they want to solicit donations for advocacy, fine.. but there are plenty more noble causes worthy of support. Tying it to manufacturing drugs is just bizarre.

<comment><USER9> This does go towards establishing medical utility and changing the laws. They say they will use the money to distribute psilocybin for free to researchers running medical trials, to develop protocols and applications for a medical trial in Oslo, and for general campaigning.

</comment></comment><comment><USER10> Now, does supporting this can make you prosecutable for financing a criminal organization under anti-gang law?

I am asking this seriously.

</comment><comment><USER11> If I understand this correctly, the recipient (backer) is responsible for obtaining necessary legal documents and approvals for medical use. They might just end up putting a lot of people in danger of possession of drugs if this is not handled properly. But +1 for looking into psychedelics, specifically MDMA, with an objective lens and clearly demystifying their position in the drug world.

<comment><USER12> Unless I missed it, nowhere on the page does it say the backer is also the recipient. There is no donation level where you get MDMA or Psilocybin for yourself, it's all produced and distributed for free (through unspecified channels, but assumedly with some more due diligence and responsibility than just mailing it out indiscriminately to everyone who backs the project.)

Looks like you can get a box "from the future" which indicates to me it's concept packaging so you can show you support the cause, not an actual box of drugs.

</comment></comment><comment><USER13> I'm not sure what the goal of this project is. It seems to be to produce psilocybin and MDMA, but it fails to mention why this would be necessary, or why they'd need any money to do so at all (apart from the modest cost of precursor). I'll admit that I don't know much about synthetic psilocybin manufacturing, so I'm talking about MDMA mostly. (but until last year, you could buy 'only add water' growing sets for shrooms in smart shops here (=Netherlands), so how hard can it be?) Either way, there are many syntheses known, most of them (although I'm not a chemist, so I don't have first hand knowledge) available to chemists with very modest understandings of chemistry and rudimentary equipment needs. I'd imagine they already have labs in which they can produce high quality product using high-yield syntheses.

With the right paperwork (which you'd need to get access to this project's product), any researcher could just as easily get access to precursor and make exactly what they want (be it MDMA, MDA, MDME, or any other variation Shulgin described, or invented afterwards by others). Plus it's easier to get licensed for owning e.g. saffrole than it is to import MDMA!

So maybe he's saying that they can do it cheaper? I doubt so, or at least I doubt that the price difference would be relevant. MDMA available underground in Europe has been more pure and cheaper than it ever was before; a gram of pure MDMA costs 20 euros retail (that's about 10 doses) if you're buying from the most expensive guy you can find. If you buy by the 100 grams, you can get it for half or a quarter of that price. So we're talking less than a euro per dose here - at a worst case estimate. After taking everything into account, I have a hard time imagining cost being a factor here (the low price on the underground market being a fascinating topic itself here - how can these clandestine manufacturing gangs make real money on their operations, after counting for the high cost of doing business?) (and before anyone says that you don't know the quality of what you buy on the black market, these people are professional pharmacologists, they could easily check quality of a sample - until a few years ago, you could get your pills checked at raves for free FFS).

Now if they're looking for a million dollars to fund drug legalization work, then fine, that's a worthy goal in itself - but that's listed only in passing in the project. So the only conclusion left is that this project is a PR stunt, where they're using a headline grabbing project description to fund much less exotic advocacy work.

(my comments in this thread make it seem that I have first hand knowledge about these things, but it's been well over 15 years since I last used or even saw illegal drugs. I just have a an interest in the economics and law of underground (drug) markets, and I read case law, reports from our equivalent of the DoJ, papers from academic researchers and government drug monitoring agencies to keep up to date. Hey, other people collect stamps.)

</comment><comment><USER14> test

</comment><comment><USER15> I think there was a documentary on knock off MDMA which the Chinese and other countries are making and selling as x.t.c. but are actually Bath Salt.

</comment><comment><USER16> I have several problems with this:

First of all, creating an account just to submit a commercial link? That should be a bannable offense, unless we are cool with marketers selling their stuff here.

Second, I'm fairly sure this campaign goes against Indiegogo's term of use. I would expect an actual ban there.

Third, and more to the point: I could get behind such a campaign if the money went _first_ towards legal access and _second_ to production. The campaign may use as many nice words as they want, but ultimately, they are not putting their money where their mouth is. They "will support EmmaSofia's work to legalize recreational use"... after collecting a nice 300-600K, and only if people pay 400K extra for it. Call me skeptic.

And all of that without getting into the legal aspect of it, which I don't like either.

<comment><USER17> To be far this is HackerNews, a discussion board backed by a business accelerator program and home to startups and VCs alike.

If there's anywhere that should be okay with commercial promotion its here.

And that's what I like about the place. No where else on the internet can you find people at the ground level, promoting themselves and engaging in discussion. If you want to ask hard questions about the product, its hard to do it to a billboard in time square, but a lot easier to do against someone who's promoting it on HN.

<comment><USER16> Although I see where your comment is coming from, I think I should nitpick that the posts from actual startups backed by YC cannot be voted on nor have comments enabled. So unless they have the courtesy of showing up in an "unofficial" post, you cannot actually ask any questions, hard or otherwise. I wish I could link to it, but the best I can do is a screenshot[1].

More to the point: call me negative, but I think that fomenting a "post and run" style will lead to a situation in which you find it increasingly harder to talk to the actual creators. I'd rather not see "send link to HN" become yet another item on the self-promotion checklist.

[1] [https://imgur.com/q7CsY0U](https://imgur.com/q7CsY0U)

<comment><USER17> Isn't that just the hiring posts? YC companies do regular posts as well which can get comments.

To be fair, you're right post and run is a bad concept, but a lot of that happens already and its simply downvoted before it ever makes it close to the frontpage.</comment></comment></comment></comment>


Write Less Code - <AUTHOR> http://mikegrouchy.com/blog/2012/06/write-less-code.html <comment><USER2> Any day that has a negative LOC count is a good day :)

This usually means I found a good refactoring, or a good abstraction that removes a lot of stuff that is now boilerplate.

If I can also add a feature with a negative net LOC count, it is a gold-star day :)

That being said, sometimes just dumping a pile of code that passes tests, but is large (bloated), unwieldy and redundant is the right move. It give me something to refactor and abstract, and gets things done.

It's all about balance.

<comment><USER3> I'm with you. The most rewarding thing about diving into a large codebase is that you have many opportunities to refactor while you add features. At my current job I add only marginally more code than I delete. Feels good. :)

<comment><USER4> Sure -- as long as there are tests and some semblance of order. Trying to add new features to an untested ball of mud is just about the worst possible thing one can inflict on a poor programmer.

<comment><USER3> Yeah, luckily, the guy I'm working with is quite good about testing. If that weren't the case, then I'd have a different opinion…

</comment></comment></comment></comment><comment><USER5> I would go even further: to be a good developer you have to hate programming. If you like to fiddle too much, you'll waste time messing around and bikeshedding instead of taking your time to think about the problem at hand at a more fundamental level. Sometimes you solve a programming issue without writing even one line of code, but challenging the business requirements instead. It's important to be holistic.

<comment><USER6> I wouldn't say "hate" programming, people who hate programming tend to write the worst overcomplicated code because their idea of re-use is copy-pasting the same bit of code they found online into every place they think it will fit and changing it around in various ways in different places so it becomes very hard to abstract later. They also like to stick with the same set of now deprecated APIs they learned 10+ years ago which means that it becomes hard to take advantage of newer libraries which were not built with these in mind, meaning that you will do a lot of wheel re-invention or shimming. They tend to think of economizing on effort and brain usage _right now_ rather than economizing on technical debt in the long run.

There is also sometimes a trade off between saving time for the programmer and saving time for others. For example a manager might want a feature that saves them 10 minutes of time once a month when they want to produce a particular report but may cost programmers several hours a month just keeping this feature up to date. In this case it comes down to who's time is more valuable.

The best way to explain this to people is in terms of "tax" (since everyone hates that). I was once asked by a management type "I used to get all my changes turned around same day, now I seem to wait weeks or even months. What's going on?"

Of course the simple answer to this question is that a year ago the program was about 10Kloc , now it's more like 200Kloc. It's also much more "mission critical" than it was. A year ago the program was small enough that I could easily imagine all the consequences of making a change in my brain so I could do basic testing and push to production, now a small change can have many consequences so it has to be thoroughly tested first.

So the analogy to make would be the government building infrastructure for say the road network. The upfront cost of building is $x , but when doing that you commit to $y spending per year (in terms of cost+time) to keeping that going.

Persuading people not to add functionality they don't need is a good idea of course, but this isn't always going to be practical. Firstly it assumes that the developer understands every aspect of the business well enough to evaluate this, in which case they really may as well just put the developer in charge of the whole thing.

It's also partly a political issue, I've spent months adding features to codebases that I know for a fact are not required because somebody with enough influence simply insists that it will be important. There is only a certain level of argument you can get into before you get to "do as you are told", that level will of course depend on many non-technical factors.

Another interesting point is that I find sometimes people will request feature X because they are perusing a line of though that will eventually lead them to conclude that they actually need feature Y. In many cases feature Y may be easier to implement (or maintain) than feature X but they simply haven't reasoned that far ahead yet so will insist that they want feature X now but acknowledge that they may change to feature Y a few months down the line.

<comment><USER5> "I wouldn't say "hate" programming, people who hate programming tend to write the worst overcomplicated code (...)"

No, this is just being slopy. Developers who "hate" code will __always __push to deal with the smallest amount of it, so they think twice before they touch the keyboard.

"Persuading people not to add functionality they don't need is a good idea of course, but this isn't always going to be practical. Firstly it assumes that the developer understands every aspect of the business well enough to evaluate this, in which case they really may as well just put the developer in charge of the whole thing."

If he doesn't understand the aspects of the business and doesn't have any stake on the final product he's not a developer, he's just a programmer doing repetitive work at a software factory - "code monkey" on jargon - and is not in a position to provide the kind of disruptive, ten-fold improvement software is able to produce.

In fact, I can only feel sorry for any business which depends fundamentally on software and doesn't have a developer as the main stakeholder.

<comment><USER6> _No, this is just being slopy. Developers who "hate" code will always push to deal with the smallest amount of it, so they think twice before they touch the keyboard._

I guess it depends on how you define "hate". The amount of effort you put into your job tends to some function of how much you enjoy it and how much money you are paid. At a certain point the money tends to tailor off in effectiveness too.

If you hate your job then your main motivator is "how soon can I go home today?" or "how little brain power can I invest in this?" you will not be interested in the LOC count of the project at all. If you enjoy programming then you are more likely to want to expend more effort thinking about how you could write the same thing using less/more maintainable code. There are of course programmers who will over architect solutions but this is usually because they believe that they are creating a structure that will keep LOC count lower over the long run.

After all code saving things like MVC/ORM frameworks were originally used by the early adopter more enthusiastic programmers.

I would say it's better to hate large bloated codebases, but I can't think there are many programmers who create these on purpose, it is usually a by product of flawed assumptions made in earlier stages or less skilled programmers.

 _If he doesn't understand the aspects of the business and doesn't have any stake on the final product he's not a developer, he's just a programmer doing repetitive work at a software factory - "code monkey" on jargon - and is not in a position to provide the kind of disruptive, ten-fold improvement software is able to produce._

Again this is sort of semantics, most companies will advertise positions that are repetitive "factory" jobs as "developer" positions. In fact some of the better programmers I know refer to themselves as "code monkeys" so I guess this is really a cultural thing.

It's an interesting point about automation and how much stake a developer should have in a business. Most businesses now depend fundamentally on software in one way or another, for a glaring example of this see the UK banks that have had to cease pretty close all activity for the best part of a week because of a software problem. Also pretty much also businesses above a certain size have _some_ custom code running somewhere.

Does this mean that all businesses should have a developer present at board level? Also should that board level person simply be someone with development experience or should they be involved in the day to day code production so that they can understand all of the decisions made?

This also ties into the debate about who should learn to program, for example do you get that experience at board level by teaching executives to write programs or instead do you promote programmers to board level and teach them about "business stuff"?

<comment><USER7> You don't have to love the ride to enjoy the trip. Programming is just a means to an end. We love the end, not the mean. He's not talking about worrying "how soon can I go home today". You do have a powerful motivator, which is the awesome software you're gonna build. You wanna write code because you wanna see your own thing built and working. Not because you love writing text on the editor.

If I could build great software without writing code I would. Unfortunately we're not there yet. As you said it yourself, most businesses now depend fundamentally on software. So being inside and working to make your code base as good and maintainable as possible, and understand those processes is important. So we do care about writing good software. But not because we love writing code, but because we hate that.

<comment><USER6> Right, but that's not an especially incitefull distinction to make. I imagine there are very few programmers around who love programming because it means they get to type lots of characters into a text editor in the same way that nobody enjoys sex because it means they get to exercise their hips.

In fact this is probably a big motivator in the number of open source libraries available now, they were developed by somebody who wanted to achieve thing X but they needed to create byproduct Y in order to do that.

So it makes sense to share by byproduct Y with the people who need to make thing Z.

</comment></comment></comment></comment></comment></comment><comment><USER8> Some of my favorite quotes about programming ( <http://quotes.cat-v.org/programming/> ) make precisely this point:

" _One of my most productive days was throwing away 1000 lines of code._ " -- Ken Thompson

" _Deleted code is debugged code._ " — Jeff Sickel

And probably my favorite (because this doesn't apply only to lines of code):

" _The cheapest, fastest, and most reliable components are those that aren't there._ " -- Gordon Bell

<comment><USER9> "The cheapest, fastest, and most reliable components are those that aren't there." -- Gordon Bell

Just to clarify. I think what he means by that statement is that, we assume that components not yet built would be cheaper, faster and more reliable than they would be in reality. Which is almost always true.

[EDIT: Just realized, it's true the other way around too, if you eliminate the need for a component, it becomes the cheapest, fastest and most reliable component.]

</comment></comment><comment><USER6> I find as a general rule, the more that my application tries to abstract and protect the user from the "technical" nature of the platform the more code I have to write.

For example I produced a CMS that was intended to be used by content writers who were not technical. However as the complexity of the website increased (more dynamic content on pages etc) I had to write a lot of code because there were a lot of exceptional cases "I want this side bar to appear on all of these types of pages apart from these 3 because of condition X and this other one because of condition Y". This means that my code ends up being an enormous pile of if statements with a huge number of database flags at the backend and checkboxes on the front end.

In the end it proved more effort efficient to produce a simple tag language for the front end and expose that to the designers and content writers, this took a lot of complexity out of the back end which could then concentrate on providing the primitives for the tag language.

You do move some complexity to the front end here for sure, but people are often better at specifying what it is they mean if they can actually generate and tweak it to some extent themselves and show the result rather than trying to explain everything in an email.

Another great example of this is Unix command line utilities , the basic interface for many of these has remained relatively unchanged since the 80s whereas GUI applications seem to be continuously redesigned.

<comment><USER10> Part of the zen of Python is "Flat is better than nested". Until recently, I always thought of this at a code block/function level. Recently I realized that this is also important when modularizing and adding layers of abstraction. The more layers of abstraction (from foo.bar.baz import Baz) you add, the more code you write and have to "keep in your mind". This presentation by Jack Diederich at PyCon 2012 really opened my eyes to the potential problems of adding layers of abstraction via modules and classes: <http://pyvideo.org/video/880/stop-writing-classes>

<comment><USER11> Interesting you say that; I would argue (and have) the exact opposite. Good abstractions, by their very nature, reduce the amount of moving parts you have to keep in your head at any one time. When the number of "moving parts" created by your abstractions outnumbers the actual bits its abstracting, then you know your design took the wrong turn somewhere.

<comment><USER10> > When the number of "moving parts" created by your abstractions outnumbers > the actual bits its abstracting, then you know your design took the wrong > turn somewhere.

This is an interesting point which I agree with and is usually where I end up. In the past I've started from the opposite end, creating multiple modules, class hierarchies, etc. This future proofing has made things harder for me to follow/understand when reading at a later date. It has become tiresome and now I consciously start at the other end, making the simplest thing that could work. Layers of abstraction then come naturally as needed.

<comment><USER6> This is the best approach , but it is best combined with fairly comprehensive re factoring otherwise you end up in a situation I have been in a few times where you have new code that runs with a nice abstraction and old code that works with less abstraction.

At that point you can introduce bugs because somebody modifies the old code in a way which would not be allowed under the new abstraction and then the new code ends up reading data produced by the old code leading to a cascade of failure.

</comment></comment></comment></comment></comment><comment><USER12> Code you never write never breaks. It has astonished me how much code people can crank out. It does not astonish me that they spend most of their time maintaining things they've written.

<comment><USER13> > Code you never write never breaks.

... but doesn't do anything either. :P

<comment><USER12> You are jumping to the assumption that the code you _do_ write does anything at all.

<comment><USER13> Such a short sentence I wrote. How do you make such assumptions about my assumptions.

<comment><USER12> Because I've been around the block enough to know that if you think code not written doesn't do anything, then code you write MUST do something. The reality is most code does nothing (other than push data around), and the actual code that really drives the value is primarily an innovation that lives in one component of the code-base. All other code is expendable and most of it is putting a pretty face on the raw functionality or adding usability, options, etc.

All code needs to be taken into account holistically. Sure, you added some code that sends alerts. It actually does something. Well, do your customers care? Are they willing to upgrade to the latest version? Does that piece of code actually change the business strategy, market penetration, or mindshare? 90% of the time code is checking boxes against competitors or providing some benefit that does not have a huge impact to the bottom line of the business. Again, MOST code.

So I make assumptions based directly of years of experience. Most of the code anyone writes barely does anything. The amount of code that is written compared to the amount of code that actually makes meaningful changes to the business or the world at large is probably 50:1.

<comment><USER13> Honestly, as a data point... you were wrong. I was just being a smart ass.

If I had any thought in mind besides just to be a contrarian it was, to quote Voltaire, "A witty saying proves nothing.".

I've been around the block a bit too and I know that these articles on HN and the one-line summations of "write more code", "write less code", "write purple code", "Code you don't write doesn't have bugs", etc. don't really mean anything more than my stupid "... but doesn't do anything either. :P".

It's like throwing people random tools out of a toolbox. "When you do carpentry, use a chisel", "For building houses, a hammer is what you need", etc.

If the carpenters you're throwing a chisel to don't know how to properly use a chisel, then just throwing one at them isn't helpful. If they already know how to use a chisel, then you're not helping them either.

Maybe you were just trying to give them a clever-sounding quote with an obvious rejoinder to throw out on HN and thus promote a little discussion? In that case, I guess it worked well enough. :)

<comment><USER12> Everyone enjoys a little conversation and a little snark :)

</comment></comment></comment></comment></comment></comment></comment><comment><USER9> My principles with software development are simple. Code should be clean, beautiful and do exactly what you want it to do.

I agree with the advice doled out by the author about spending more time on thinking than actual programming. This is something most good developers eventually learn as they get more experienced. To immediately dive in and implement as you find issues would cost you more time in the longer run.

Also, putting it on paper always helps. Especially when you're dealing with large software or changes to complex algorithms. It helps to visualize it on a more permanent medium than the brains fickle whiteboard.

Ultimately, unless you work on the software like you have a stake in it, you wouldn't spend enough mind on it to do the continuous re-factoring and improvements it takes to make great software. This is especially true in a commercial environment where deadlines and releases and user visible improvements are the focus of the management. It is upto you to care about what happens under the hood and eventually you will wish you had.

</comment><comment><USER14> One of my favorite reads lately:

"The problem is largely philosophical: as software developers we're trained to think in terms of rigid systems of objects, design patterns and re-usable code. You might set out with the great idea to build a system of classes with clearly defined interfaces that inherit from one another when specialized behavior is needed. You might model all this in Lua using any number of class and inheritance patterns to try and enforce your vision. But, if you're perceptive, you'll soon start to suspect that all of the work you're doing to build an architecture really doesn't add much practical value. You may find yourself in the situation of having spent a lot of time defining a traditional OOP-style inheritance hierarchy and a big pile of fancy data structures only to realize you've created nothing more than an especially convoluted way of initializing tables.

Fortunately, there's an easy solution: don't do it. "

From : [http://getmoai.com/wiki/index.php?title=Structuring_Your_Moa...](http://getmoai.com/wiki/index.php?title=Structuring_Your_Moai_Game_in_Lua)

</comment><comment><USER15> From a product owner's or designer's perspective this would be "add less features" which is an equally good idea and also requires less code.

</comment><comment><USER16> _If we wish to count lines of code, we should not regard them as "lines produced" but as "lines spent": the current conventional wisdom is so foolish as to book that count on the wrong side of the ledger._ \-- Dijkstra

(I got this from akkartik but can't remember where.)

</comment><comment><USER17> 'Spend more time writing less code.'

I think that quote, or something like it, is from the 80's.

I've found this is the hardest thing for non tech business partners to understand, because most of the time, it appears as if you are doing nothing.

</comment><comment><USER18> I think this applies on every scale. Not just writing more elegant code but also just writing code in smaller units and having a prejudice against large methods/classes/components. I've noticed a lot of devs have a mental block about things like one-line methods or extracting a single conditional test into a method and other trchniques that really do help make your code clearer.

The more experienced I get the more I come to view big code as an anti-pattern / code smell.

</comment><comment><USER19> the job of a designer is it, to let things look beautiful in different ways: in the way it looks, it feels, how to use it and so on. i wouldn't say that i'm only a software engineer, but also a software designer.

      code == ui

code has to look beautiful, it should feel good to work with, easy to use, etc.

maybe this is all about the zen of coding.

</comment><comment><USER20> If you find a way to avoid writing ASCII codes, or avoid it most of the time, then you aren't programming. And therefore, you are no longer a programmer.

Arranging, configuring and connecting components/widgets with GUIs is a very powerful way to solve all sorts of problems in many application domains. Unfortunately, the more powerful a system like that is, the less attractive it is for 'software developers' because it means they mostly aren't writing code, but rather are dragging around widgets.

I'm building a system like that anyway, for my own personal sanity. It is definitely a tool for advanced software developers to create, publish and configure widgets, not just for users or designers, although its also specifically for users and designers as well. I expect that most software developers will not appreciate it because it will make it too easy to build powerful applications without writing code.

The biggest thing holding back software engineering right now is source code.

The problem is that the definition of programming and software development is outdated. Programmers write colorful ASCII codes.

<https://github.com/ithkuil/cureblog>

<https://vimeo.com/43784316>

</comment><comment><USER21> The obligatory relevant bit of Apple/Bill Atkinson folklore (posted to HN previously):

[http://www.folklore.org/StoryView.py?project=Macintosh&s...](http://www.folklore.org/StoryView.py?project=Macintosh&story=Negative_2000_Lines_Of_Code.txt)

</comment><comment><USER22> "Code is a by-product", remind me to Atwood's Please don't Learn to code.

<comment><USER5> Code is a by-product of software development in the same sense as a blueprint is a by-product of engineering. Teaching a programming language doesn't turn someone into a software developer just as teaching technical drawing doesn't turn someone into an engineer.

<comment><USER23> I think you're being a bit free with the metaphors here.

A blueprint isn't a finished deliverable if you want something that you can actually use. Code, on the other hand, mixes design and building - if you delete the code, what are you left with?

<comment><USER5> Yeah, I'm playing with metaphors here. The point I want to get across is the code itself is just a means to an end. _Just_ the code is often not a deliverable, unless you make money from software patents. Google doesn't make money because they sell a lot of code. Facebook doesn't get investment because they wrote a lot of code. That doesn't mean their code isn't valuable - it is. But it's the actual computation (e.g. execution of this codebase) that has real value. Get it?

<comment><USER23> That attitude leads to devaluing software, followed by bugs, a legacy codebase and not being able to extend your software when your competitors catch up. Programs and the problems that they solve are intertwined. You can't easily separate them - which is why your metaphor doesn't work.

</comment></comment></comment></comment></comment><comment><USER24> there is no universal truth other than balance and careful judgement. Say "write less code" to the wrong person, and they will go off and create six months of meetings where they decide what they should decide what they should decide to decide to do. Analysis paralysis will creep in and kill you.</comment>


Please Review Our App:  Manage Your Searches - <AUTHOR> http://www.bitcrumb.com/blog/manage_your_searches.html

<comment><USER2> Looks pretty interesting... however a small UI suggestion.... it seems to occupy a fair amount of the available screen space. How about something like a "bitcrumb powered searchbox" in the browser itself as opposed to a panel on the left??

<comment><AUTHOR> That's a great idea, it would be an elegant solution to the screen real estate issue. Thanks!

</comment></comment><comment><USER3> The thing is, this is something I'd like Google and YouTube -- especially YouTube -- to store for me on their site. I can't test your extension because I'm stuck with Fox 2.x (slow PC), but it does sound interesting and might fill a need.

<comment><AUTHOR> Thanks Mike, we wanted to take advantage of some functionality that is available only in the newest versions, and then in the very near future get it also working for older versions.

You make a good point about Google, YouTube and other sites just storing this directly. Ultimately that's definitely the direction the web's heading.

One point that is worth considering is that it is somewhat useful to have all of this together in one place, rather than "walled" into separate sites all over the web. That's something we've done in this app, that it would be tough for any one site to do.

</comment></comment><comment><AUTHOR> If you are like us, you do a ton of searches across different sites, and you don't bookmark the searches, and your broswer history just captures them chronologically. That kind of works, but we are moving towards a world where people need to recall their searches from multiple devices, across multiple browsers, from any location.

This is a tool we built to try and help with that, and we'd love to hear what you think.

</comment><comment><USER4> just a small suggestion: May be you can put a small video on the website explaining what bitcrumb does and how does it work.

<comment><USER5> Will do so soon, after we buy our first tuxedos. btw - I am the other half of BitCrumb.

<comment><USER4> hey nice to meet you... although i haven't really : )</comment></comment></comment>


Tesla supplied just 208 Model X cars in 2015 - <AUTHOR> http://www.theguardian.com/technology/2016/jan/04/tesla-supplied-just-208-model-x-cars-in-2015 <comment><USER2> _" just 208 cars were actually delivered in the fourth quarter of 2015 [...] In fact, by the end of the year, it was producing 238 a week."_

So, supply is outstripping demand? Or do they have a problem delivering cars to customers? Or is it just latency between 'produced' and 'delivered'?

<comment><USER3> likely still having production issues. Tesla's issue has never been creating good looking cars but in ramping up assembly. This is the real issue facing the III, not that it won't exist and look good but that they might not have the cash needed to build out the assembly line</comment></comment>


Why Aren't More Users More Happy with Our VMs? Part 1 - <AUTHOR> http://tratt.net/laurie/blog/entries/why_arent_more_users_more_happy_with_our_vms_part_1.html <comment><USER2> _why did CPython running the Mandelbrot benchmark have a running time of 134.419s and an incredibly wide confidence interval of ± 32.347s? I had no idea, so, in the best tradition of VM measurements, I buried my head in my sand and hoped that no-one would say anything. They didn't._

A beautiful summary of the field!

 _In other words, this VM is highly optimised for this benchmark — but no-one ever ran it long enough before to notice that performance gets much worse over time._

Perhaps, although more likely, they noticed; and then in accordance with tradition, promptly buried their heads in the sands.

\---

Since this thread is likely to be read by people who care about unexplainable performance glitches, I'll highlight an otherwise inexplicable ~20% run-to-run performance drop that I recently saw an explanation for: [https://www.realworldtech.com/forum/?threadid=179700&curpost...](https://www.realworldtech.com/forum/?threadid=179700&curpostid=179700)

There has been a lot of talk about whether AVX512 is of real world benefit. One big issue is that it's so power hungry that the entire core compensates by slowing down whenever 512-bit instructions are executed. What's not well known is that with an AVX512 capable processor running the common Ubuntu 16.04, you may well encounter this slowdown even if your program never uses AVX512.

More specifically, there is a problem with the way that some versions of glibc are saving and restoring the 512-bit ZMM registers. Even at program start-up, the upper 256-bits can be in a "dirty" state, which can cause the core to slow down to the "AVX512-light" speed on any SSE, AVX, AVX2, or FP operation. Patches for glibc were backported as far at 2.25, but Ubuntu hasn't included these fixes in their updates.

The bottom line is that if you are working on an AVX512 capable system, you should probably make sure that you understand this bug before publishing any benchmark results.

<comment><USER3> Just for completeness, this problem with AVX is biting even when using containers instead of VMs.

<comment><USER4> Just for completeness, the "VM"s in this article have nothing to do with containers. But of course we all read the article before commenting and we all know that, right?

Without being an expert in virtualization or containerization, it seems pretty obvious to me that if a certain instruction causes thermal throttling, then that'll cause thermal throttling whether the instruction is issued from a host OS or a guest OS or for any other reason. Indeed, the more layers of abstraction involved, the likelier you are to hit the problem.

</comment></comment></comment><comment><USER5> One thing I am struggling to understand is why do we need JIT in the first place? What would be wrong with statically compiling java or c#? Portability is nice but the reality is that almost no one uses it. Typically you have to create different packages for different platforms anyway just because of the installer. Most backend applications are designed to work on a single platform (who is running a mixed windows+linux/x86+ARM backend for the same binaries?). For front end applications, most platforms have different UIs, and all new platforms (android, iOS) have incompatible APIs anyway.

Is there a fundamental benefit I am missing?

<comment><USER6> The theoretic fundamental benefit is you are able to optimize for code paths practically occurring during the runtime with particular set of data or inputs. There is no way to know that at compile time, hence it's often touted as a way to make things "faster than C" with sufficiently smart JIT compiler.

But of course no JIT compiler ever is sufficiently smart and any execution path benefit gained is lost to poor cache discipline of VMs. And the whole JIT/hotspot concept was really a hindsight attempt to get away from abysmal performance of VM based languages.

<comment><USER7> There is another very practical benefit: You can use all features available on your PC.

E.g. when you compile an application C-style, you set the target architecture to the lowest CPU you want to support. If this is , say, SSE, then no SSE2 instructions will be used by the program and the sometimes huge performance gains from them are lost.

A VM like hotspot can generate code for this specific machine. If you have SSE2, it will generate SSE2 instructions. If you dont, it wont.

Recently, I see more applications choosing code paths based on CPUID, but this only works for CPUs existing at compile time. If you app was compiled in 2016, in wont use CPU features from 2018. If your java app from 2016 runs on a JRE from 2018, it will use them.

<comment><USER6> I would really like to see a Java program beating a C program in this use case. Say, outperforming it (or even matching to same order of magnitude) on DCT/IDCT even by using SSE2 vs SSE/MMX. Can only say am immensely sceptical.

Another thing is these kind of gains with instruction level efficiencies are exceedingly rare and your typical VM program never runs any code where SIMD extensions would make a difference.

<comment><USER7> This article is not what you ask, but it is an example of a VM beating native:

[https://nullprogram.com/blog/2018/05/27/](https://nullprogram.com/blog/2018/05/27/)

Java uses the same technique.

Basically, a JIT allows you to skip the overhead of the GOT.

Devirtualization is another case.

I have personally seen Java beating an existing C++ program for the reason I describe, but I cant publish the results here. You have to program carefully or you loose all speed benefits because of pointer chasing. But it is possible.

<comment><USER8> > Basically, a JIT allows you to skip the overhead of the GOT.

This is a problem that is GNU/Linux-specific. Windows DLLs are not PIC (position-independent code), so they do not suffer from this problem and don't need a GOT.

See

> [https://www.symantec.com/connect/articles/dynamic-linking- > li...](https://www.symantec.com/connect/articles/dynamic-linking-linux-and- > windows-part-one)

for details.

The method that Windows uses is much faster in the average case, but slower in the "bad" case. So GNU/Linux vs Windows have different performance tradeoffs.

<comment><USER7> Yes and no: there is another indirection mechanism at work on windows: All results for imports in the import table are at the beginning of the DLL's data segment. So a call to another DLL first has to fetch the data from there, then do an indirect call. In x86 assembler:

      some_import_address    dd some_import ; will be filled in by dll import
          [... lots of unrelated code and  data...]
          call [some_import_address]

a JIT can read the address from code and do directly:

          call some_import

that's one less memory load.

The benefit is that the dynamic linking does not modify the code segment, so there are less private, modified pages mmapped, thus more sharing and less memory usage.

</comment></comment></comment></comment></comment></comment></comment><comment><USER9> Am I reading that right? There is a whole article about how long JIT compilers take to settle, but the actual performance changes by just a few percent tops? (for example, first graph has 0.571 for cold JIT, and 0.568 for warm JIT, a 0.5% difference)

I think for me, the main takeaway from article is startup time for JITs is irrelevant, since it does not affect performance much.

<comment><USER10> In general, yes, you're reading the timings right, but there's a couple of factors to consider.

First, the JIT compiler has often done most of its work during the first in- process iteration, so the plots are not generally following a "one in-process iteration is slow, then the JIT kicks in from in-process iteration 2 onwards" model. Put another way, the JIT compiler is often making even the first in- process iteration run pretty fast.

Second, I would suggest that the often small timing differences are more worrying than they may first appear. In a semi-mature compiler, optimisations are frequently in the range of a 0.5-1% improvement. So if your measurements are only accurate to (say) 2%, most of your attempted optimisations will be misclassified (bad optimisations will sometimes be measured as good; good optimisations will sometimes be measured as bad). Furthermore, when a VM recompiles things, it generally performs several optimisations at once. Thus, if the overall performance gets worse (even if by a small bit), it may suggest that several optimisations performed badly at the same time.

<comment><USER11> But doesn't that mean the article's point is kind of moot? That when people blame slow languages / VMs, they actually _are_ slow and it has nothing to do with warm-up time?

<comment><USER12> Both can be true, benchmarking JITs is really hard, but even so, (despite decades of claims to the contrary), managed VMs actually are a bit slower than unsafe native code.

<comment><USER13> Nothing prevents native code from being safe

</comment></comment></comment></comment></comment><comment><USER14> Interesting stuff. To learn that it can take 190 iterations for warm-up to finish may be a revelation to VM developers.

The idea about some runs having slowdowns might not be significant if it's just one run out of 30 that does it though. The result in the last Diagram of TruffleRuby on spectralnorm having 25 slowdowns and 5 no steady-state is interesting.

Full paper at : [http://soft-dev.org/pubs/html/barrett_bolz- tereick_killick_m...](http://soft-dev.org/pubs/html/barrett_bolz- tereick_killick_mount_tratt__virtual_machine_warmup_blows_hot_and_cold_v6/)

</comment><comment><USER15> It would be interesting to see how much wall clock time these applications run for. One answer to the question of how many iterations to run for is to compare it to the expected running time of real applications. If the expected running time is minutes, and the VM hasn't warmed up after ~1 minute, then it's pretty irrelevant whether it would "eventually" warm up or not. This would be one way to side step the halting-problem-esque question they've gotten themselves into with respect to how long to run the benchmarks for (which I'm pretty sure is intractable).

</comment><comment><USER16> Is anyone able to link to the krun software used?

What do people use to make their computers stable for benchmarking?

<comment><USER10> The best place to start with Krun is its GitHub page [https://github.com/softdevteam/krun/](https://github.com/softdevteam/krun/)

</comment></comment><comment><USER17> How do I make LaTeX tables like that?!

<comment> another-cuppa Using booktabs for a start. There are various other packages for making tables nice but that one gets you a long way. Also study well typeset tables to learn why they look nice.

<comment><USER18> >study well typeset tables to learn why they look nice.

Can you link to any resources that discuss this?

<comment> another-cuppa I don't know any. What I meant was just to find good looking tables yourself and study them with an eye for typesetting. The manuals for LaTeX packages, including booktabs, are often very good too.</comment></comment></comment></comment>


Ask HN: Will the software industry come out of Covid-19 stronger or weaker? - <AUTHOR> Will the software industry be weaker or stronger 12-18 months? <comment><USER2> Well for starters we should see an uptake in remote work positions. Now that software companies have been forced to test it for 3 months... They hopefully won't go back to the old way of doing business.

Or companies that already did remote work have been able to continue to operate as close to normal as possible.

</comment><comment><USER3> Software in our industry will continue to exist until the Internet dies or the last human does. Pretty sure it's going to get stronger. I'm starting my second project in quarantine.</comment>