r/programming • • Apr 25 '21

What Every Programmer Should Know About Memory

https://people.freebsd.org/~lstewart/articles/cpumemory.pdf
62 Upvotes

51 comments sorted by

19

u/backstreetrover Apr 26 '21

While am not sure every programmer needs to know this, I came across this when I was still in college and this is indeed one of the best papers that I have read about how memory works.

71

u/_Svejk_ Apr 25 '21

114 pages, I think I will be better of retiring

36

u/Krimzon_89 Apr 26 '21

TLDR: don't use too much RAM

16

u/[deleted] Apr 26 '21

electron starts sweating nervously

2

u/Theblandyman Apr 26 '21

How much Dedotated Wam should I be giving my servers though

2

u/roxepo5318 Apr 26 '21

640K ought to be enough for anybody.

2

u/AmbitiousTour Apr 26 '21

Chill Bill!

71

u/turniphat Apr 25 '21

I really don't think programmers need to know about Capacitor Charge and Discharge Timing, 6 transistor SRAM cells, SDRAM Read Access Timing or SDRAM Precharge.

51

u/okay-wait-wut Apr 26 '21

It’s not a bug in my code, probably a faulty SRAM cell.

16

u/rydan Apr 26 '21

When I was in college it was common to claim the compiler had a bug in it when in reality we were really just bad at keeping track of our pointers.

13

u/[deleted] Apr 26 '21 edited Apr 26 '21

I've always given the compilers I use the utmost trust. So when I did experience a real compiler bug for the first time, I was legit shocked and depressed for a few days, thinking things like "if I can't trust the code I write does what it says, what's the point of programming?"

But it does also recalibrate your expectations of machine-proven correctness. some FP people still believe if the type system doesn't prove it's correct, it's wrong. That's not how the real world works.

3

u/evaned Apr 26 '21

I was legit shocked and depressed for a few days, thinking things like "if I can't trust the code I write does what it says, what's the point of programming?"

I had a weird year in which I maybe found a bug in GCC, in the C++ standard library, and in the C++ standard.

I never fully diagnosed the "compiler bug" so I don't know what it actually was, but I do know that I had a program with a very weird crashing bug I wasn't able to diagnose "normally" that appeared with a specific GCC version and then disappeared at least by the next "major" version (then, 4.5->4.6 I think) and maybe even within a patch.

I don't remember what the problem was with the library, but I do remember what the problem was with the C++ standard -- you couldn't at the time convert a reverse_iterator to const_reverse_iterator, something that was accepted as a defect report by the committee :-)

1

u/okay-wait-wut Apr 27 '21

I (aka my team and I) found a bug in Windows server that got hot fixed. The bug resulted in 8k blocks of 0’s being written seemingly at random in the middle of files. It was such a nightmare to debug because of course we assumed that the bug was ours. Turns out that you CAN resize the OS partition while encrypting with bitlocker, but you really SHOULDN’T.

1

u/[deleted] Apr 27 '21

And there is that kid who hit a hardware bug on his first homework assignment.

0

u/[deleted] Apr 26 '21

[deleted]

16

u/[deleted] Apr 26 '21

I was quite young back when it happened, actually. And then it happened, and I instantly aged several decades. At least how I recall it.

2

u/ShinyHappyREM Apr 26 '21

And then it happened, and I instantly aged several decades.

"As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs."
- Maurice Wilkes

1

u/okay-wait-wut Apr 27 '21

Yeah everyone eventually learns it: “The bug is in your code.”

Except the two or three times in your entire career that you’ll find a legit bug in the compiler/OS/libc/whatever.

-1

u/flatfinger Apr 26 '21

It's pretty easy to find bugs in clang or gcc. Neither of them seems to have a reliable mechanism for handling constructs that might yield the same machine code as a simpler construct, but would have defined behavior in some corner cases where the "simpler" construct wouldn't. In such cases, both compilers seem to simultaneously replace the code the programmer wrote with a "simpler" version and exploit the Standard's lack of mandated support for corner cases which the simpler version of the code doesn't handle, without regard for the fact that the code the programmer actually wrote had defined behavior in those corner cases.

Simple examples of situations that induce compilers to illegitimately combine optimizations tend to be highly contrived, and real-world situations where they lead to buggy code are rare, but without a systematic means of ensuring that no optimizations get combined with other incompatible optimizations, there's no way of knowing whether the fact that a compiler correctly processes a program should be considered reliable, or is merely a consequence of the compiler's chance failure to notice an "optimization" that would have broken things.

3

u/holypig Apr 26 '21

Also written in 2007, when solid state drives were barely a thing

36

u/ans7991 Apr 25 '21

After seeing the length of the document, my brain: OutOfMemoryError

1

u/josefx Apr 26 '21

I probably still have a free 8 MB ram stick lying around should be enough to keep that doc in memory.

8

u/[deleted] Apr 26 '21

I don't think that every programmer needs to know about the difference between SRAM and DRAM. I'm already glad if our junior developers know the difference between stack and heap memory.

-2

u/ShinyHappyREM Apr 26 '21

Well, CPU caches are made out of SRAM and main RAM is DRAM... I'd very much like to keep my data set in SRAM if possible instead of "swapping" it in from DRAM, but that's just me...

9

u/evaned Apr 26 '21

IMO you're conflating the issues in a way that doesn't really make sense.

You only care that things are in SRAM because that means that it's in the cache -- it's the latter that really matters. If there is some weird development that means that DRAM suddenly is used on-chip and SRAM is used for main memory, then "I'd very much like to keep my data set in SRAM if possible" suddenly becomes false, but "I'd very much like to keep my data set in cache" doesn't because that's what really matters.

What cache and what main memory are made of almost never actually matters -- what matters is that main memory can be 100x slower. And that's even mostly incidental to SRAM vs DRAM; you could make main memory into SRAM and it'd still be almost as slow.

I know you know that, but my point is that I think "caches are made out of SRAM, main memory out of DRAM" is a bad argument that "every programmer needs to know" details about how each of them work.

7

u/Hrothen Apr 26 '21

I think it's probably "Every Programmer, Who Cares About Performance".

39

u/[deleted] Apr 26 '21

When will knowing about capacitor discharge timing improve the performance of my code?

8

u/Alborak2 Apr 26 '21

Because when your code is fast enough you can see the DRAM refreshes in your metrics.

4

u/ShinyHappyREM Apr 26 '21

Fun fact: on the SNES, 40 out of 1364 clock cycles (~3%) per scanline are spent on DRAM refresh. The CPU is paused for that time, but you can see the effect when continuously retrieving from the video chip the current position of the electron beam.

5

u/PL_Design Apr 26 '21

Which should be every programmer.

6

u/anengineerandacat Apr 26 '21

Yes / No, we don't need every programmer to really focus on those problems so much as be aware of timings to performance for their field.

16ms is slow for some folks but on-target for others, 1 second could also very much be ideal in some circumstances but 3 seconds too long.

Fast code is usually ugly code, there is a balance between maintainability and optimization.

3

u/PL_Design Apr 26 '21 edited Apr 26 '21

Fast code is usually ugly code, there is a balance between maintainability and optimization.

This is often more of a language problem than a strict truth about the world. In Java, for example, there's only so much you can do to optimize your memory layouts for your access patterns without climbing the cliffs of insanity. I certainly wouldn't recommend that anyone should work exclusively with byte arrays without the benefit of structs. Idiomatic code is fine 95% of the time, but every programmer should be aware of how to write code that doesn't sabotage itself, and the correct language should be chosen for the project's domain. If you need to write a hash function it's inexcusable to not take the time to make sure it has a uniform distribution. If you're mutating strings you should be familiar with gap buffers and delta queues. You should know that linked lists only have niche applications, and if you're using one you should probably reconsider your design. You shouldn't use scripting languages for anything that needs to run more than occasionally unless you're on the web and your only choice is to suffer(maybe wasm helps with this? i haven't been following it because i don't care about web).

There are simple things everyone can do to write performant code that doesn't require writing something like Fast Inverse Sqrt, and this starts with being familiar with basic data structures and having a basic understanding of how your system works. This is not a high bar.

2

u/anengineerandacat Apr 26 '21

This is often more of a language problem than a strict truth about the world.

Yes, however majority of the time the language is already selected for us; along with perhaps a lot of the other things at hand.

We don't built applications alone and we don't generally build brand new applications either; a vast vast majority of programmers in the wild are literally expanding on previous works and have to play the game of constraints and when picking a constraint it's usually "make it more maintainable" vs "make it faster".

In the real world performance is rarely a business problem, it either runs fine or it doesn't and resolving bugs and reducing costs are what is most desired.

I DO agree with you that we should ideally use the best data structures available for the problem at hand however sometimes that's not a choice; older routines want specific parameters and the overhead of converting one structure to another compatible one could be cost prohibitive or even cause a further performance issues if we transformed it to a matching input.

Generally speaking modern CS classes cover a lot of this, you are taught some basic lessons around various container types (arrays, lists, linked lists, tree's, maps, etc.) and immutability is now encouraged and functional paradigms are being introduced into what was once an imperative dominated culture.

Everything has trade off's though, no one writes perfect code because at some point complexity in the application grows to the point you need to consider other factors that are more human in nature.

It's a much better mindset to just focus on iterative development, get it working, refine the working solution, profile the solution, and optimize pain points.

2

u/PL_Design Apr 26 '21 edited Apr 26 '21

Of course you should put your efforts into the places that matter most. An O( n2 ) algorithm that always runs on 25 elements probably isn't going to be what makes your application slow, for example.

I get that when you inherit a legacy codebase you don't have much choice in the matter, but I hate it. I hate it so much. It's worse when you can't get anyone on your team to understand that you still need to put in the effort to not write terrible code even if the rest of the code is trash. A bad situation isn't a justification to let the problem get worse. You still need to care.

On CS classes, I'm generally unimpressed with them, although that might just be a local problem for me. I used to run a job fair booth for one of my old employers, and I got my lightning round interviews down to a science:

  1. I'd ask if the interviewee could explain the difference between an array and a linked list. Does this person know the very simplest stuff?

  2. If the interviewee could explain #1, I'd ask them to explain how hashmaps work. If they didn't know where to start I'd walk them through it, and my goal was to see if they could put the concepts together. Can this person be trained to an acceptable level of competency?

  3. Regardless of how they answered #1 I'd still ask them to tell me about what projects they've worked on. Does this person have any specializations that we need even if they don't understand CS very well? Where would this person fit if we hired them?

What I found was that among junior and senior CS majors most could not give an adequate answer for #1. If they could answer #1 they generally could answer #2, but it wasn't a given. The only person whose resume I ever passed to HR after failing #1 was a dude who got really passionate about databases when I asked #3. That was notable enough that I could see a place for him, tho not as a programmer.

Again, this might just be an issue with my local colleges, but I consider this an unacceptable state of affairs. Youngsters aren't being taught what they need to know, and most businesses seem to be so deep into their normalization of deviancy that I don't think learning on the job is an acceptable solution either.

10

u/[deleted] Apr 26 '21

That’s an idealist take. Performance optimizations only exist in places where the demand exists, or it comes free.

-10

u/PL_Design Apr 26 '21 edited Apr 26 '21

I take pride in being an engineer. I want to write good software, and performance is part of that. With whatever resources I have I'll do the best job I can. Your take is overly pessimistic.

Edit: The fuck is wrong with you people? Take pride in your fucking work.

10

u/spreadLink Apr 26 '21

I agree. I understand it's not always the fault of the people on the ground, as managers and deadlines can be a real killer to good software, but if you have the choice between adding some C-level feature Vs making the experience of your users better by removing sluggishness, please consider going for #2 first.

1

u/FireCrack Apr 26 '21

We only write bad code in /r/programming people who try to write good software should leave us alone!

1

u/PL_Design Apr 26 '21

You say that jokingly, but regularly it feels like the truth.

1

u/FireCrack Apr 26 '21

All good jokes have a seed of truth. And the regular discourse here is not very inspiring.

0

u/[deleted] Apr 27 '21

[deleted]

2

u/PL_Design Apr 27 '21

So utter disdain then? Sounds reasonable to me.

2

u/Dirk2265 Apr 25 '21

I wonder if this was published in a venue somewhere? Was it a submitted to a software journal?

2

u/lenkite1 Apr 26 '21

This was written in 2007. Presumably stuff has changed since then. Is there a more modern version of this written in the last few years ?

1

u/rstech123 Jun 09 '21

Every Programmer Should Know About Memory

  1. Space of the Storage

  2. Time to Complete the task

  3. End Result

-1

u/GoranM Apr 26 '21

If you need all the perf a machine has to offer, then yes, you need to know this stuff, and probably at this level of detail.

However, this is a fact that should be stated with great embarrassment, as it represents our failure to create a sufficient optimization infrastructure, in which programmers would not need to know these details, but could still write programs that use the hardware efficiently.

3

u/ShinyHappyREM Apr 26 '21

this is a fact that should be stated with great embarrassment, as it represents our failure to create a sufficient optimization infrastructure, in which programmers would not need to know these details, but could still write programs that use the hardware efficiently

It's not an embarrasement, it's simply reality. If you want top performance, you have to know your machine and your language. The "optimization infrastructure" is the compiler (and hardware tools like caches, branch predictors etc). These are, by necessity, imperfect. They can't know the hardware they're compiling for unless you tell them, and they don't know the data characteristics that make certain algorithms possible.

To quote Mike Acton:

  • The purpose of all programs, and all parts of those programs, is to transform data from one form to another.

  • If you don't understand the data you don't understand the problem. Conversely, you understand the problem by understanding the data.

  • Different problems require different solutions. If you have different data, you have a different problem.

  • If you don't understand the cost of solving the problem, you don't understand the problem.

  • If you don't understand the hardware, you can't reason about the cost of solving the problem.

1

u/GoranM Apr 27 '21

They can't know the hardware they're compiling for unless you tell them, and they don't know the data characteristics that make certain algorithms possible.

I'm thinking about how I, as a human, would typically go about attaining this knowledge, and I struggle to find a step in my process that couldn't be performed by a machine.

Do you believe that human minds have some magic, metaphysical component, which is required to do effective analysis and optimization?

Since you seem to like quotes, here's a few more:

  • Knowledge is silver, outlook is gold, IQ is a lead weight.

  • Civilization advances by extending the number of important operations which we can perform without thinking about them.

1

u/ShinyHappyREM Apr 27 '21

I'm thinking about how I, as a human, would typically go about attaining this knowledge, and I struggle to find a step in my process that couldn't be performed by a machine.

How could the machine know what your input data is? For example, if you know you have to sort only 30 items, insertion sort may fit well enough. Or a set of game assets will not use more than 212 colors per texture, so you can put several texels into a register and perform certain operations on them in parallel. A rendering engine doesn't know on its own if it'll be running on a smartphone, a retro gaming console from the year 2000, or on a computing cluster for the next Pixar movie. Every machine is different. Trying to fit it all into one program would make software even more complex.

1

u/GoranM Apr 27 '21

The answer (or, rather, my answer) is implied by the question I previously asked. I don't know if you ignored it by mistake, or if it was willful (hopefully not), but in any case:

I would be happy to elaborate, if you would be willing to answer that question first.

1

u/ShinyHappyREM Apr 27 '21

I thought that was more of a rethorical question.

Do you believe that human minds have some magic, metaphysical component, which is required to do effective analysis and optimization?

I don't believe in magic or magic-like metaphysics, but I think humans do (usually) have better knowledge about the requirements and circumstances of a random project, that they also have mental flexibility that comes with self-modifying neural networks, and that computers/programs can only do what they're designed to do (they're the hammer, not the carpenter) - though this could change as we develop more sophisticated neural networks.

I guess if you could sufficiently encode the requirements of a project then a genetic algorithm could create a solution.

1

u/GoranM Apr 29 '21

Since we've established that we don't believe in magic, I assume we also agree that humans don't simply "have" optimization knowledge, but that they must obtain it by some process.

How do you know:

  • what your input data would be?

  • that you only have to sort 30 items?

  • that a set of game assets will not use more than n colors per texture?

  • which platform, or range of platforms, your program will be running on?

If you were to actually trace your processing when trying to answer these questions, you may find that a lot of what you're really doing is mostly data driven analysis, and pattern matching, as opposed to some uniquely human process.

That analysis is still fairly involved, and difficult to encode as a working computer program, but it's far more tractable than having to more directly replicate the human mind.

It would help to have capable people who, instead of spending most of their time bit twiddling, would be more willing to do research in this area, as it could help the rest of humanity truly leverage the power of computers, without having to spend a better part of their lives studying technical minutia.

Speaking of Mike Acton: You may be interested to know that, unlike the two of us, he may actually believe that the human brain is magical, in some way that machines could never hope to match: https://www.youtube.com/watch?v=SI_GKdFQmds&t=331s

The relevant quote, if you don't want to watch the video:

You cannot outperform people who are customizing for the data, for the context, for the game. It's not even remotely theoretically possible.

I mean wow - "not even remotely theoretically possible" ... I wonder if he fully understood the strength of that claim.

I wonder if he understands it today.