Fun fact: in case of writing a tight loop, that gets executed million times per second, the following:
if (hour >= 24) hour -= 24;
can be much faster than a modulo. It makes a difference in case of writing things like cyclic buffers or open hash maps for algorithmic competitions - the modulo might become the most time-taking operation.
But in code like this, or business code, or especially if you write a public method where you don't control the input - please use modulo.
That's neat to hear. I'm curious, I'm surprised because it has an if statement and could mess up a processor pipeline if it was false. Not saying you're wrong I only have the bare minimum computer architecture to graduate CS. Also do you know why wouldn't modulo be implemented under the hood the same way since it's faster?
To get a real result you will have to benchmark your application, since performance effects of branches really depend on the application. If the branch is easily predictable, then it will incur almost no penalty, and a subtraction is fast to do then modulo. You can't implement modulo like this, because in most cases it isn't faster to do repeated subtraction. But if you can guarantee, that your variable (in this case hours) will never get as big as 2*maxValue (in this case 48), a single if + subtract is enough.
Also if you need to calculate a modulo with a value 2^n, then it can be simplified to a logic AND condition (clearing the last n bits)
Thanks for the explanation, I appreciate it š. Also I feel like an idiot for forgetting that modulo is more general than a simple if/subtract. That makes alot of sense.
So, I really wanted to know now and wrote a small microbenchmark for a super simple Circular Buffer (if you want to see the code, it is here)
On my Ryzen 7 1700, the Modulo tests take about 60% longer with G++ and -O2! (the second run, the first one is a warmup)
In reality the difference would be lower, because Circular Buffers are mostly used for Communication between threads where you also need some kind of atomic writes / synchronization which have overhead.
Also interesting:
When changing the Buffer size to a power of 2 (in my case 256), the compiler can optimize the modulo operation by doing a logical and. That made the Code with Modulo Operator 2x faster, then the if case!
It really depends. For some scenarios, when writing tight look in C, using condition + subtraction/assignment instead of modulo can be even 2x faster (on some architectures). In a comment below i posted a quick benchmark.
If you want, I wrote some details about it below. Yes, it can screw with your processor branch predictor. Modulo can't be implemented like that "under the hood", cause if we want to replace modulo a = a % mod we need to first be sure, that a is in range [mod, 2*mod). The optimizer usually isn't smart enough to notice such condition by itself.
It might use a conditional move rather than a branch for something as simple as one subtraction. And actually on x86/x86_64, doing it that way makes the comparison unnecessary, since the subtract instruction sets all the same flags. So that if statement can be boiled down to a single subtraction and a single conditional move.
If it's faster or slower depends on code AND the CPU. Some can do a modulo instruction (yes, some architectures have that) about as fast as an if followed by a jump or even faster.
So what you should write heavily depends on where it's going to be executed.
PS: sometimes compilers even check this good enough to just go and replace it with the faster thing, no matter what you wrote in code
That's why I wrote "can" be faster, not certainly "will".
The problem with compiler replacing the code like this, is that there are a few preconditions here, that the compiler not always can see. If you want to replace subtraction with modulo, you need to be sure that for: a = a % mod, a is less than 2*mod.
Another thing, that makes it vary a lot, is whether you want to get modulo for a constant or variable mod. For a constant, the generated code will try to use bit representation tricks. See: https://godbolt.org/z/9qrbMMbY4 , and switch between -O2 and -Os. Output for x86-64 architecture.
There are a few more things when it comes to optimizing modulo, like signedness of the value. See: https://godbolt.org/z/nY1cTb8rq. Unless the compiler knows, that the value is non-negative, it can't use some bit tricks.
Another thing here is a branch predictor. It depends heavily on architecture and code. Writing for modern desktop CPUs you can usually assume, that sequences of tests with results TFTFTFTF... will be correctly guessed. It's always good to give extra information to the compiler, if you are able to, with something similar to GCC __builtin_expect.
I'm really curious about architectures, that have fast integer modulo. I'd love to read more about them, if you have some links or sources.
And to any new programmers reading this:
IN ALMOST ALL CASES IT IS A PREMATURE OPTIMIZATION.
Always measure first. Don't optimize prematurely. The tricks described there are often platform, compiler and architecture dependent. For higher-level languages like python it will never affect performance of your code. For languages like C#, Java, most likely not, and if it does, you probably got a wrong tool for the job you are doing. Only in languages like C, C++, Rust, Golang and similar you can gain noticeable performance benefits from writing code this way.
@edit: Here you have a quick benchmark for Clang, running on some AWS machine: https://quick-bench.com/q/ofgm7F8bfW5gQbiND41a_W2zX9U Version with comparison is only slower than power-of-two trick done on unsigned values.
If you are incrementing by a small amount, it is faster to conditionally subtract a few times instead of doing a modulo operation. If the value of hours can be in the millions or billions however, it will not be faster.
For competitive algo, you could even use a branchless hour -= (hour >= 24) * 24.
Edit: This snippet (in c) produces identical assembly to if (hour >= 24) hour -= 24 in GCC, but in Clang, the if-statement actually produces better-optimized code. Branchless programming, and any other optimization that looks like a hack, is almost always a premature optimization and should only be used after measurement.
Dang, I was all ready to point to an instruction throughput table and call this out, but integer division is still way slower than I thought on the latest geeration of CPUs (and slower still on CPUs even a few years old).
Even 8 bit division on Zen 3 takes 10 cycles -- although I'd still probably take the 20 cycles of a 64 bit division over a missed branch + a bunch of instructions for the cmp.
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/KaznovX, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
Personally I like using this even when not strictly necessary because then I know it belongs to object, which is especially important for inherited members and classes I'm not too familiar with.
Oh, I may have formulated it a bit misleading: I meant with exception that you usually don't name local variables the same like a global one. So the set-method is one of the few places where it is common practice to have the local variable and global variable named the same. So an exception to the rule that you don't need to use 'this.value'.
Yes, same in C#... personally I find it a bit of an antipattern to unnecessarily use the this unless necessary (usually in like a constructor/setter argument. Just because if there's any ambiguity, you have a class-too-big or more likely a method-too-big problem. I recognize it's probably a controversial opinion.
I think this is new-ish. I havenāt touched Java in years but helping my little sister with her CS homework I discovered that it was a thing now. Anything to make thingg GB s less clear, I guess.
Like a clock. If its currently at 23 hours and you added/advanced by 27 hours... the value of hours should be 2. He was doing a repeated subtraction to do it and I told him to just use %. So he replaced the - with % and I found that funny.
Ahhhhh, this makes sense now. Iām not sure if OP and student are Americans, but I can say as an American our primary schools donāt do a great job teaching modulus. I donāt think I ever heard that from any of my teachers.
I donāt think I even really āgotā modulus until I started getting interested in cryptography. Itās so weird that we teach long division and remainders, but donāt try to connect that to more formal mathematical concepts.
(I will say that in fairness PCs were just starting to become a thing normal people would have when I was in a school, so Iām sure things have changed a little since then).
I wouldn't say that, but it's definitely a use-case specific thing when I do choose to do it. I developed a library that has a boolean true/false for whether to output an additional log, so a simple one-line looks way better to read than 3 lines with curly braces
I disagree. I think that braces should always be used, regardless of the case. Omitting them will make maintenance more difficult and it offers the possibility that someone will just add another line to the ābodyā and not realize that it will not be part of the statement or loop.
There is a single acceptable case to omit braces, and that is putting all on the same line. However I would discourage that, though that is a somewhat subjective preference.
However, in the example of this post, they would absolutely be necessary.
No, and actually your suggestion makes sense given the purpose of the program. But, as I'm sure you know, modulus returns the remainder after performing a division operation. Thus, it's not exactly equivalent to what your naĆÆve co-worker wrote, bc if the user inputs a number that 24 can go into multiple times (e.g. 49), the modulus returns 1 while your co-workers code would have resulted in 25. Obviously, this is impractical since the hour should never exceed 24 - actually, 23 w/ regards to 24 hr time, as the standard is to start at 0 for the first hour, but I digress - however, a user who inputs an edge case would find that numbers greater than 24 would still work, while your co-workers code would not bc edge cases such as 49 would result in numbers greater than 24 . In conclusion, your modulus solution is actually better thrice-over bc it's more concise, readable, and works with edge cases.
When I see the use of multi-line conditionals without an specific block I usually refer to goto fail heartbleed and why it happened. It doesn't matter if one is a great or a bad coder, it only takes a tired evening to make an error out of an error-prone approach.
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/BackgroundBright, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
285
u/KaznovX Mar 27 '21
Fun fact: in case of writing a tight loop, that gets executed million times per second, the following:
can be much faster than a modulo. It makes a difference in case of writing things like cyclic buffers or open hash maps for algorithmic competitions - the modulo might become the most time-taking operation.
But in code like this, or business code, or especially if you write a public method where you don't control the input - please use modulo.
113
u/jonnysteps Mar 27 '21
Oh goodness....
Also, is hour a global or something? I'm curious how that gets defined.
26
u/Tunro Mar 27 '21
Now im confused too, Id write
hour = (hour+incValue)%24
I guess
4
u/[deleted] Mar 27 '21
What is this code even trying to do? I'm so confused lol
3
u/[deleted] Mar 27 '21
Here's my improved version:
24
u/-Dueck- Mar 27 '21
This person is next-level confused
8
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Mar 27 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
14
u/chrisnlnz Mar 27 '21
Assuming this is a junior developer? I don't know, harsh to make fun of..
32
u/[deleted] Mar 27 '21
Removing the braces is a cardinal sin
4
u/geon Mar 27 '21
The code is broken. Add more than 24 hours.
1
u/CartographerFlashy73 Mar 27 '21
Um...but what if hour is a higher multiple of 24? You might want to reject that edge case, you know b/c of user error.
3
u/gabrielfv Mar 27 '21
When I see the use of multi-line conditionals without an specific block I usually refer to goto fail heartbleed and why it happened. It doesn't matter if one is a great or a bad coder, it only takes a tired evening to make an error out of an error-prone approach.
1
u/BackgroundBright Mar 27 '21
using % is also a bad idea. just do
2
u/ForeignerLove Mar 27 '21
Whats up with modulo operator bad code in last times lol
2
u/ayojamface Mar 27 '21
I just make hour = 0, which is probably exponentially worse.
1
u/Inopmin Mar 27 '21
Fascinating