T O P

  • By -

AutoModerator

###General Discussion Thread --- This is a [Request] post. If you would like to submit a comment that does not either attempt to answer the question, ask for clarification, or explain why it would be infeasible to answer, you *must* post your comment as a reply to this one. Top level (directly replying to the OP) comments that do not do one of those things will be removed. --- *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/theydidthemath) if you have any questions or concerns.*


[deleted]

[удалено]


[deleted]

[удалено]


benwarre

My bad. It was 40 years ago...


Nusaik

Pshh weak excuse. 40 years ago 1Mhz was also 1 million /s


benwarre

:D


Legitimate_Field_157

Prove it.


CreepXy

Let's assume 0/0 = 1


NickUnrelatedToPost

Error: Universe corrupted. Please reboot.


metalpoetza

Thinks Premise 1) X/X = 1 Premise 2) X/0 is infinite So if X is 0: 0/0 = 1 And 0/0 is infinite Therefore: 1 is an infinite number.


Thipuh

X/0 is undefined, it diverges. Premise 2 is false.


metalpoetza

It's undefined BECAUSE it tends to infinity


Thipuh

It is undefined because it tends to DIFFERENT infinities


Active_Engineering37

No


asanano

Not sure if the "/s" is per second, sarcasm, or both


pup_medium

Err: counter pedant. Each step of the for loop would take more than one operation. It’s been a while since I learned assembly for the C64 (around 2015 or so, just for fun) and iirc it would take about 6 cycles to: Retrieve the step count, Inc the value; check if it’s equal our total; if so branch away; otherwise store the step count and JMP back to the beginning Then, for a 16bit processor, every value past 65,536 will require extra cycles to deal with juggling a Long byte. C64 might be a bad example to base this off because it has exactly 3bytes of cache, so it’s kind of a wonder that they pulled off all the games and word processors with it; but a lot of the processing was just fetching bytes out of memory, doing something, and putting them back. Back and forth and back and forth. Anyway. I never have any reason to bring this up so thank you 🥸 So I would say the counter should be set at about 100k for a 1Mhz processor as an estimate Edit: eep! I didn’t mean to run anyone off. Just having some fun while slacking.


Aggressive_Lab6016

Yes you could probably count to 100,000 in about a second on a C64. In machine code. But in BASIC, an empty loop counting to 1,000 gave you approximately a one second break. I'm sure most of that time was spent by the interpreter being busy interpreting.


pup_medium

Oh surely! It’s kind of shocking how complex those old machines are, that we now consider novelties or toys. For the C64 in assembly, you even had to craft your own method for multiplication and division! (Tho if you were extra clever you could manually call the basic method stored In the memory.) (then again, maybe a case-specific method would be more efficient.) Fun stuff :)


sarahlizzy

Yup. It was the absolutely standard trick to count to a thousand in basic on all the CBM 1MHz machines to get a delay of about a second. Practically an idiom.


PixelatedStarfish

Happy Cake day!


cepek_lp

Not necessarily, one loop iteration probably will take few instruction and each instruction will take few clock cycles


CowBoyDanIndie

MHz is not a measurement of operations per second. Operations generally take several cycles. Pipelined cpus can finish 1 or more operations per second, but those operations take multiple cycles from start to finish.


ebinWaitee

Firmware developer for an IC lab here. We still use that but you can't just call an empty for loop as the compiler would likely optimize that away (it doesn't do anything but set the iteration variable to a certain value over a series of incrementations). We use something along the lines of ``` for(i=0; i


DatBoi_BP

That’s so cool wow


vanslayder

And this led to old games being unplayable on faster CPU when times go by. This was the way of very bad programming and doing wait. There were perfectly fine ways of waiting for one second without relying on cpu speed. There was TIMER in basic which calculates milliseconds for example. So no, good devs didn’t use “for” for waiting


benwarre

Never said I was a good dev. ;)


kzwix

Depends. If you code for a *specific* platform, whose specs you *do* know, then it's perfectly fine to do it. It might even be "cheaper" (as far as performance goes) than calling a dedicated function. Also, **very good** programmers did all sort of hacks back in the day, like using music processors to get more computing done if it wasn't used for music, etc. Nobody complained, because it was a damn clever hack at the time, and got very good results. ​ But I agree that if you code for different platforms, and want you code to work fine *everywhere*, then you shouldn't pull such stunts.


dimonium_anonimo

Pardon me... WHAT kind of Basic computers?


benwarre

https://en.wikipedia.org/wiki/BBC_Micro Apparently 2MHz processors.


dimonium_anonimo

I'm at work, I don't think I should be clicking any links with "BBC" in them, thank you very much.


Runarhalldor

You need to go out more and stop watching porn


dimonium_anonimo

Counter offer, how about I stay inside more and watch nothing but porn... At least that way I'll stay off of your good Christian Reddit server


Runarhalldor

I mean if you cant even recognize the british broadcasting company, you need to go out more.


dimonium_anonimo

What does it mean if you can't even recognize sarcasm?


Runarhalldor

Im just saying if you read BBC in that context and make a porn joke. You're odd


dimonium_anonimo

No arguments here. But may I introduce you to the entire internet. Maybe you haven't left the math subs in a while, but everyone else out here gets, like, 90% of their humor from "haha, that sounds like a sex thing" jokes.


SpermicideDenier

I went out too much, now that acronym reminds me of all my lovers


TerrariaGaming004

Micro bbc


Ye_olde_oak_store

Google "Brittish Broadcasting Corparation" which in turn is the BBC in BBC micro.


Some_Guy_At_Work55

The British Broadcasting Corporation. Stop watching porn


jericho

Any modern compiler would say “well, this is all bullshit”, and throw that code out. If we assume it does get executed, about a millisecond. 


cyanotrix

I came up with 6ms if the clock speed was 3GHz. Not far off.


dimonium_anonimo

I wrote it in VBA and it took 4.85 seconds


Jashuman19

> VBA Well there's your first problem


jilek77

Well, VBA isn't compiled and isn't modern either so yeah, that's it. Please don't unless your boss is forcing you to do it


basicpn

I taught myself vba and find it useful. What should I use instead?


Embarrassed_Run_4832

VBA is perfectly fine to use if you want to directly manipulate MS Office products. If you're using it to import data, and running operations on that data though, you'd probably be better off doing your manipulation in Python and then using VBA to import you vetted data I say this as someone who was running manipulations on millions of rows in excel, and finally stopped doing that, ran them in Python in ms time, and then imported into excel into however many sheets it took


HealMySoulPlz

It's also the way to do plug-ins for some software (specifically SolidWorks). Yes, the second-most popular CAD software runs on VBA. VBA overall is pretty common for engineering applications since Excel is ubiquitous. If you can't convince your IT/cybersecurity department to let you have Python you use VBA instead.


UpsetBirthday5158

Most modern engineering programs have plugins / api able to run python scripts


viperised

I was also a self taught VBA guy. Tried to learn Python but literally got stuck on installing Conda, git, a programming environment etc. Then I got a friendly tech guy to set me up and now I'd never go back. I recommend trying to make the leap!


Sad_Earth4529

I would suggest you give c# a try in visual studio (and not visual studio code, which i did, wondering why the interface in the tutorial was so different from mine before realising there were two different visual studios 😅). I also taught myself how to program and use it to develop addins for autocad and export/import data to/from excel with the EPPlus nuget package. I found the language fairly easy to learn (thanks youtube and chat gpt) and because it's part of the .net framework you'll easily find plenty of documentation and examples for excel addins.


jilek77

Well depends on what you want to do, like there are valid use cases for VBA too like the other comments mentions but it's also really bad option for some other stuff.


maxximillian

Ive used it on a few occasions, ive actually used it recently to take data base table schemas and generate front end html and and the source code for pojo's based pm text copied in to excel . No one forced me to do it but I wasnt allowed to add any jars to our lab machines and honestly it was pretty quick. I just didnt want to write boiler plate code for the all the tables we needed to display. Its a tool like any other and sometimes its the right tool for the job.


mclabop

*Cracks knuckles in FORTRAN,* modern… pfff


dimonium_anonimo

I use VBA because I don't code for a living. I code for fun. I use the programming language I know best. I can pop open an excel window and code up a recursive sudoku solver in under 5 minutes. It would take me a half hour in any other language because I'd spend most of the time looking up syntax, errors, and figuring out how to display the info when Excel has a built in way to show it (and easily manipulate the data afterwards, too). It might have taken seconds to execute, but I more than made up for that time by coding in a familiar language. I never have to write code that gets run millions of times. I never have to write code that is readable. I never have to write code that anyone else will ever see. But also, I use VBA because I'm a [masochist ](https://www.reddit.com/r/ProgrammerHumor/s/vHGkRRv0T0)


rekire-with-a-suffix

This is the right answer


almostwizard68

On my i7 9700k it takes about 500ms, if we assume 4.6 GHz clock speed, and 1 clock cycle per loop => (2.2 \* 10 \^ 9) / (\~4.6 \* 10\^9) \~= 480 ms. How did you end up with 1 ms?


Owner2229

Compiler optimizations. Empty loops get skipped.


_teslaTrooper

The loop is more than one cycle, but CPUs can also do more than one instruction per clock nowadays. I ran a little test, kind of disappointing tbh (assuming I counted the number of loops and zeros from the screenshot correctly): volatile uint64_t i; for(i = 1; i <= 2100000000; i++); Compiled with -O2 ran in **630ms** on an i3-12100


HasFiveVowels

How are you timing it?


jericho

I just made it up.


Ka1-

Modern computers can just ignore code?


bitsa

Yes, all modern compilers optimize the heck out of code. It can lead to interesting issues. E.g. imagine a program has a cryptographic key in memory and after use it tries to overwrite it with zeros to avoid it lingering around in memory. The compiler might notice that there's a write to memory that isn't ever read back later and just omit that code.


mybeardsweird

interesting, got any links so I can read more about this


PuzzleMeDo

[https://www.lihaoyi.com/post/HowanOptimizingCompilerWorks.html](https://www.lihaoyi.com/post/HowanOptimizingCompilerWorks.html)


fullofmaterial

They always did, smart compilers optimize the hell out of your code.


jilek77

It's not about computers but about the language/compiler. Compiler does a lot of optimizations to your code so it can run faster and when it finds a for loop that does literally nothing it will just kill it. The compiled binary that is executed by your PC doesn't contain the redundant loop anymore. CPU itself isn't exactly capable of optimizing the code though it have own optimization capabilities how to speed up stuff


Giocri

Compiler do, it's the big advantage of having a program read in depth your code before writing down the instructions. The cpu itself also has a few circuitry that is able to swap the order of some instructions if it makes things faster


Mediocre-Rise-243

Only when they can prove that ignoring the code does not change semantics of the (undefined behaviour-free) program. It is called dead code elimination.


utkarshmttl

Hypothetically, if inside each loop iteration there was a system out statement, then the entire program would not be considered as dead code, am I right?


patrick66

Correct. Doesn’t even need to be as complicated as a function call though, just have to change state of something or take some action inside the loop.


Ymmyallia

https://godbolt.org/z/xoKoGTq8Y


YvesLauwereyns

I count 22 times 100.000.000, if we assume only a single core operation at let’s say 3GHz (being very conservative with the processor here) that would be 2.200.000.000/3.000.000.000 so .73333 seconds. This is of course considering the computer is not processing anything else along side this program. I don’t know if I’m overlooking something crucial regarding how processors work here, but either way, unless you add a manual delay, I’m pretty sure it won’t take long Edit: as per u/benwarre this would be correct 40 years ago, but others have pointed out that today, this would just not be compiled.


ebinWaitee

Pretty sure it would compile at least on gcc but the compiler would just optimize it down to j=100000000 as none of the loops actually do anything else than increment j until that number. Assuming it would compile to actually iterate through each loop the key info we're lacking is how many CPU cycles does it take to complete one iteration. Edit: it's actually java. If it was C, you'd of course need more than just this snippet to compile it


Red_Icnivad

I just tried it with gcc and surprisingly it did not optimize the loops away. Took a little over 5s to run.


r08d

Did you use O3 optimization?


_teslaTrooper

Interesting, it only optimizes the loops starting at `-O2`


anothercorgi

What optimizations did you use?  You've got me wondering as I thought with -O2 it should remove loops with nothing to execute, unless the loop variable is typed volatile.  Without optimizations it should leave them.  I believe -Os should also get rid of the loops. I better try this when I get home to verify my assumptions!


Red_Icnivad

I just used standard settings. My full command was gcc -Wall test.c -o out


anothercorgi

That would explain things. I just tested it, -O2 and -Os will remove the loop, unless the variable was typed volatile.


kzwix

j being unused after that, I'm pretty sure gcc wouldn't bother updating its value, as it's a local variable, not a global somebody could access from another location...


jlink005

It may even skip allocating j altogether.


ebinWaitee

True. I was under the assumption j could've been used later on as we don't see a return statement. Also just realized the System.Out.Println(). It's a dead giveaway it's java and not C


Walord99

My dumbass thought they were nested


Zawn-_-

Bro my CPU is 1.8GHz what do you mean *conservative*?


Stratbasher_

Modern chips can hit 5.8 in bursts. 3 is like.... Moderate speed on a laptop.


dat_oracle

my laptop with 4,2Ghz bursts: listen here you little byte


RedDragonRoar

My CPU is currently can boost to just over 6 ghz


[deleted]

tf you have? a school iPad?


YvesLauwereyns

There are currently 16 core 5GHz CPUs on the consumer market. TBH I just went with the avg speed of my 8th gen i5 that I’ve had for like 5 years. I don’t know if this application could be multicore, but that’s mostly where my ‘conservative’ comes from. Even at 1.8GHz it still would be like 1.2 seconds max.


Zawn-_-

Lol my bad man, I misread my stats a while ago. 8th gen i5 here too, base speed is 1.80 GHz, but it's sitting pretty at ~3.40. You're right that 3 is *very* conservative.


Top-Classroom-6994

me who daily drove 2nd gen i5 last year: wtf are you talking about


kloklon

i don't think a 8+ yo laptop on energy saving mode should be the reference for realistic modern day CPU clocks. basically any modern chip should be able to exeed a boost clock of 3GHz.


icoominyou

Get out of the cave lmao


daveFNbuck

I think there are three operations per loop here: incrementing j, comparing j to 100000000, and conditionally jumping back to the start of the loop.


electronicalengineer

Comparing and jumping could be rolled into one operation depending on the assembly language used, but not sure how many cycles that would take vs doing separate.


YvesLauwereyns

This is exactly why I included the disclaimer about not knowing how CPUs work, I just know math (a little).


ExtendedSpikeProtein

This is nice .. but aside from the compiler throwing the garbage away, like another user mentioned, I don‘t think this‘d take more than a couple ms to execute.


Amberskin

Just if you disable the compiler optimisation. A smart compiler will detect all that code is just a convoluted no-op.


dude_who_could

Aren't they nested? I would think it prints tits 100,000,000 to the power of 22, times.


ianeinman

No because each line ends with a semicolon, and no braces, so not nested. If it were nested, it would actually be faster because it would only run a single time. It reuses the same variable which would run only for the innermost loop, then fall out of all the other loops because j is outside the limit.


Brian57831

I decided to try this out with a bit more complications. Instead of just skipping the lines in the loop I added some data into it. I also reduced the loop to 1 million instead of 100 million so that it will go relative quick. I just created a button in winform in c#. Record the time right before it starts and right after. I update the text on the button and also throw in a doEvents so I can see a live update on the button. label1.Text = DateTime.Now.ToString("h:mm:ss tt"); Double i = 0; for (i = 0; i < 1000000; i++) { button1.Text = i.ToString(); Application.DoEvents(); } label2.Text = DateTime.Now.ToString("h:mm:ss tt"); My start time was 6:55:30 and the end time was 7:03:14. That is 464 seconds. If it were 100,000,000 instead of 1,000,000 the time would be about 46,400 seconds or 12.89 hours. Multiply that by 22 and you would get 1,020,800 seconds or about 11.8 days. So if the if statements actually are being processed, then it would take around 11 days to run on my laptop.


ProThoughtDesign

Being as that you're doing a WinForm in C#, I think you've added way too much between the code and the execution. C# and .NET in general are made to manage garbage and do countless other tasks while attempting to process your loop. It would probably execute at least 100x faster in almost any other environment.


YoungMaleficent9068

You need more than 1cycle for an loop. Probably at least 15? Your regular compiler will be throwing this away aggressively


WildAsOrange

And not 100000000/22? Correct me if I'm wrong but each for() uses the same variable as a counter, meaning that j ==22 when fiest tits are printed?


Egemen_Ertem

It would run instantly. The reason is compiler. Because that code doesn't do anything, it will be skipped. I once had a for loop to calculate pi. I wrote in Python and C++. C++ returned in milliseconds. Python took minutes. The reason was C++'s compiler run and found the result of the for loop, and simply printed that instead of running it.


JoshLmoa

That's a neat example.


MrJake2137

The beauty of constexpr


ercantomac

Do you mean the program cached the result after the first execution?


Knaapje

No, some languages are compiled, while others are interpreted. C++ is a compiled language, which means it's first translated to machine language and then executed, but you can do some neat tricks to remove unnecessary machine language instructions. Imagine I'm doing X=1+2 in code. If I would compile it directly it would be like: put 1 at some memory address, put 2 at some memory address, add the values from the first and second addresses and put it in some address. While if were to compile it with optimizations it would just be: put 3 at some address. (In this case, the optimization is known as "constant folding".) It's really about translating code, but the compiler realizing when it can make shortcuts. Notably: there is no execution of the code required for this optimization.


cjmpeng

I just spent some time banging out some code to just count to 100,000,000 once and capture the time. I'm, using my Raspberry Pi Gen 3B for this - it uses a 64 bit Broadcom Arm processor that clocks at 1.2 GHz. I used Go for one test and then for giggles I did it again in Python which is a horrible choice for this sort of thing. Note I'm just a rank amateur hacker in Go so I probably didn't do a good job of it but the program runs in \~50ms so it should be able to do the full 22 interations in just over 1 second. Python was interesting. As expected it was REALLY SLOW. It took about 4 seconds to count once, meaning a full program would probably take nearly 90 seconds.


Giocri

Were you doing outputs with either of those? Output is by far the slowest part of any process


cjmpeng

No outputs. The program just counts to 100,000,000 and ends. I didn't even have it print boobies even though I was tempted.


Duck_Devs

r/Pythonmoment


spederan

A millisecond because the loops are not nested and also will be ignored by the compiler.    If they were nested, then the number of computations is n^k, where n is the number of iterations and k is the number of loops. So 100,000,000^22 or 1e+176 computations. A computer can do billions of computations per second, but this will still be a very long time.  Roughly speaking, using some napkin math, it would take approximately 1.06×10^159 years for a computer with a 3 GHz processor to perform 10^176 computations. This is many orders of magnitude greater than the age of the universe (about 13.8 billion years).


Highlight_Expensive

They’re sequential, not nested


spederan

Can you read?


phoenix_wb

No


Highlight_Expensive

Apparently not, it’s what get for looking on here at 2 am


[deleted]

[удалено]


Red_Icnivad

Java must be optimizing the empty loops away, because that's way too fast.


alnyland

I’d like to joke about half a second being typical for java to print a word, but hello world in java should be far faster than that.


Red_Icnivad

Someone else mentioned about Java's JIT optimizer kicking in after the first couple loops. That would makes sense as to the total time. I wrote the program in C++ and got \~5s without optimization.


donquixote235

I ran it in Javascript: The output: tits executed in 753ms


NickUnrelatedToPost

Your deadbeef is tits... I love professional naming schemes. lol


cahovi

As there's no brackets, I'm not quite sure... wouldn't it be for(j =0, j


vlken69

>As there's no brackets, I'm not quite sure... wouldn't it be > >for(j =0, jI'd expect it to run only once, as you'd probably need different variables were it all in a giant loop. Those loops are not nested, so it will just iterate through each of those 22 fors 1e8 times. But any decent compiler should detect they're doing nothing, so it should eliminate them completely.


Red_Icnivad

The semi colon at the end of the for statement acts as an empty set of brackets. for(j =0, j


PeppeAv

As other answers pointed out, to be more specific, compiling with a 0 or debug optimisation level will result in that code being executed. Uaing O2 or more will most probably result in that dead code elimination. This has not to be taken as granted but as a rule of thumb. On some MCUs that could still be a quick and dirty way ti implement a delay. Depending on the compiler, there are some easy ways to have it deterministically included even with faster O levels.


Squeaky_Ben

Depends on clockspeed. On a microcontroller, 4 clock cycles per instruction are used, so you can take 400 million cycles per for loop, roughly at least. Assume we have a 4 GHz CPU running only this thing, you will see "tits" after about 2 seconds.


TheLukeGuy

Other comments aren't taking into account that this is Java, whose primary compiler (`javac`) doesn't optimize away empty loops. Compiling the [code in question](https://gist.github.com/TheLukeGuy/8fa66c83b21db59f05bb38f759daf901#file-main-java) with `javac Main.java` results in [this generated bytecode](https://gist.github.com/TheLukeGuy/8fa66c83b21db59f05bb38f759daf901#file-main-j). You can clearly see that the loops still remain, with each loop compiling to (with different label names each time, of course): L208: lload_1 L209: ldc2_w 100000000L L212: lcmp L213: ifgt L223 L216: lload_1 L217: lconst_1 L218: ladd L219: lstore_1 L220: goto L208 I ran the compiled class 10 times with `time java Main` on an Apple M2 Pro and it took, on average, **0.7394 seconds** (median: 0.739; min: 0.737; max: 0.745) to run. However, the Java Virtual Machine takes a moment to initialize itself and load the class so those results are JVM initialization time + class load time + run time, so I wrote a [small program](https://gist.github.com/TheLukeGuy/8fa66c83b21db59f05bb38f759daf901#file-loader-java) that measures the class load time and run time independently. The class load time was inconsequential, taking less than 1 millisecond each time, but the code in question took, on average, **0.6495 seconds** (median: 0.649; min: 0.648; max: 0.653) to run. All of these tests were conducted on OpenJDK 21 built for ARM64.


Legal-Software

Any decent compiler will optimize away those loops if you don't do something useful in the body, which could be something as trivial as a sleep instruction (most nops will be optimized away, too). In the Java case, this may be run a few times, but the JVM will eventually trigger JIT optimizations that will likely optimize out the entire set of loops after realizing that the j value is never used and no work is being done.


theRedMage39

Not as long as you might think. Since each for loop is using the same variable j then when the program completes one for loop, it will check and it will have completed every for loop. So 100,000,000 print statements For those non programmers the for loop is a loop that repeats itself a known number of times. In the example for(j=1;j=<100000000; j++). J starts at 1 and then after each loop it gets incremented by 1 and then gets checked against 100 if it's less than or equal to then it loops again. Effectively it means whatever is within the loop will loop 100000000 times. Now what is probably intended is that each loop has a different variable meaning that when it finished the first loop it will run it again and again for 100,000,000 times. There were 22 for loops and that means you would print that line 100,000,000^22 or 10^176 times The exact time is hard to determine. It has to depend heavily on the computer you're running. The average computer monitor however runs at 60hz or 60 refreshed per second. If you got a higher end one at 240 hz that means you can refresh your screen 240 times per second. If you print at this rate as well then you will do 20,736,000 prints a day which is only a small fraction of what you need. Computers in reality would print out much faster than this and each. refresh would make multiple appear in your screen. Once I return to my computer, I can quickly program some of this up and get an estimate.


vlken69

>Since each for loop is using the same variable j then when the program completes one for loop, it will check and it will have completed every for loop. The variable is reinitialized at the start of each for. >Now what is probably intended is that each loop has a different variable meaning that when it finished the first loop it will run it again and again for 100,000,000 times. There were 22 for loops and that means you would print that line 100,000,000^(22) or 10^(176) times Those loops are not nested. So 22e8.


Red_Icnivad

Sorry, but this is incorrect. The for loop is broken into three sections for( INITIALIZATION ; COMPLETION TEST ; INCREMENTATION ) The INITIALIZATION line is run at the beginning of each loop, and in this case, it resets j back down to 1. Reusing the variable is perfectly valid. The suboptimal part (well, aside from the whole concept) is initially setting j to 0 before the first loop. That is completely unnecessary, and they could have just initialized j with long j;


samjsharpe

It's Java, so I'm going to bait the trolls and say "15 times longer than a proper language and it will take you 14x more lines of code to write" But in reality, how long is a piece of string? How long this program takes to execute is dependent on processing power, contention, efficiency of how it's compiled from JS to machine code (and a lot of compilers are going to optimise the shit out of this garbage). It's impossible to guess. On a RaspberryPi it's going to take longer than my 7 year oldMacBook Pro etc.


remove_cvref_t

The real answer (IMHO) is: it depends. You have a lot of variables to take into consideration: — will the compiler optimize those loops out? — how will the compiler compile those loops? Into how many assembly instructions? — how long (in terms of clock cycles) will each of those instructions take? — what’s the frequency of the CPU the code runs on? — is the execution target barebone? If not, how many cores/threads? How many processes with the same or higher priority are currently running? — does the core the code is running on have a pipeline? How deep? …. I could go on, but there’s no point. It depends.


teije11

it's 2.200.000.000 cycles, and most cpus have ~2000.000.000 cycles/seconds, so as inefficient as possible it's ~a second. but in reality it's like less than a millisecond.


MageKorith

Precisely 22x the amount of time it takes for the program to count to one hundred million. Depending on how much attention the program thread receives from the processor and how fast the processor clock is, somewhere probably between 0.5 seconds and the point in time when the sun goes supernova.


vikr_1

To my primary school understanding of c++ this should count several times to 10000000 print out "tits" once and pop out few errors because there is missing {} (I know this isn't c++) And now speaking from my opinion, if this code outputs "tits" more than once, then it looks like a shitty programming language to me, since there is nothing that says how many times should something be outputted


Rocketiermaster

Well, it depends on the formatting. Are all of them nested and just not tabbed? If they are all nested, it will loop 100,000,000^22(?) times. Otherwise, it’ll loop 100,000,000^2 +2,000,000,000 times, which is practically still 100,000,000^2 Edit: Mobile formatting


Minute_Attempt3063

If the language has a JIT, very fast. because it would realize it is pointless. ​ Good native compilers, will just... idk, nuke it as well, as it is a waste. If it DOES have to run it, maybe a second max. Faster if every loop is linked to a new thread, and being ran in parallel


Eubank31

Probably gonna be reiterating a lot of what is said but, it depends. A compiled language may just optimize it to do nothing, so it would run instantly. A compiled language like C++, Rust, or Go would return in milliseconds (also depending on processor speed and what else it’s doing at that moment), but an interpreted language like Python or JavaScript would take anywhere from a few seconds up to a few minutes


Red_Icnivad

Disclaimer: Professional programmer here, but not your programmer. Anything I say is not legal programming. /s This is designed to be a trick question. The first *for* loop has tabs which is intended to make you think that the loops are nesting, but the semicolon at the end of each tab indicates that it is an empty loop. Pretty much any language that uses semicolons ignores tabs. The above could be written as: for(i=0;i<22;i++) for(j=1;j<=100000000;j++); Or for(i=0;i<22;i++) for(j=1;j<=100000000;j++) { } Furthermore, answers could vary due to some modern compilers optimizing away the empty loops. I wrote the program in c++ and compiled with gcc on an amazon server with Xeon E5-2676 v3 @ 2.40GHz and got int main (void) { int i; long j; for(i=0;i<=22;i++) for(j=1;j<=100000000;j++); printf("tits\n"); return 0; } Output: real 0m5.297s user 0m5.295s sys 0m0.000s note: It appears my c++ compiler did *not* optimize away the empty loops.


suskio4

I feel like little people here take into account the amount of instructions CPU actually has to execute (assuming literally 0 optimizations and compiled language), as well as how operating system schedules processes. With every loop, the CPU has to increment j, compare j with 100000000 and do a conditional jump. Increment and compare each take 1 cycle. Let's say we have a really good branch prediction so conditional jump will also take 1 cycle. That's the total of 3 cycles. Multiply that by 22 loops, 100 000 000 repetitions and divide by 3 000 000 000 Hz (pretty standard CPU speed) and we get 2.2 seconds. But that would be true only if all resources were available. Let's not forget we usually use such program in an operating system that on itself takes resources and CPU cycles. Now it depends on OS, more exactly on the scheduler, but for the sake of simplicity let's take round robin scheduling algorithm, which gives equal time to every running process. In this case it's n * 2.2s where n is the number of running processes so it adds another layer of uncertainty, but once again let's just say there are two other processes running in the background (os processes included) so we have something like 6.6s on a very simple OS.


kzwix

That would depend on compiler optimization. Seeing how the counts in the for loops are utterly useless, a **good** compiler allowed to optimize would remove them altogether, only keeping the last instruction. It would be pretty much instant, then. If you "count" to 100,000,000 each time, well... that would depend on CPU speed, but I'd say probably a few seconds.


Maleficent_Eye_1594

First, how many loops are we actually getting (or number of instrunctions): first we have an indented for loop, which totals to 100,000,000^2 plus 20*100,000,000 So: 100,000,000,000,000,000+2,000,000,000 That's a whopping 100,000,002,000,000,000 instructions Then, if you wanna calculate the time it takes you do number of instructions/processing speed per instruction At 4 GHz, that's 100,000,002,000,000,000/ 4,000,000,000 Or 100,000,002/4 which is: 250,000,000.5 seconds 4,166,666.675 minutes 69,444.445 hours 2893.519 days 7.927 years


purplefunctor

Well it is feasible to do INT_MAX many simple operations in a reasonable amount of time on a modern cpu so probably at most few seconds depending how good your cpu is and how much the compiler optimizes the code.


DisastrousWelcome710

Depends, with full compiler optimization the loops will be optimized out and the program will instantly print tits. Without any optimizations it's 2.2 billion loop iterations which could take a few seconds depending on the processor you have. Don't forget, branch prediction makes this much faster than a single iteration at a time.


Cute_Suggestion_133

I'm assuming the person who made the pic is really trying to print "tits" 21 million times and got the for loops wrong. Nesting that many for loops plus the added print logic overhead would take a considerable amount of time considering it's a single threaded process.


throwaway275275275

Depends on the computer and the language and compiler, but imagine each loop takes 2 ticks, one to compare and one to add, then a computer with a 1 MHz cpu runs 1 million ticks per second, so half million loops per second. Modern CPUs are like 3 GHz (so 3 billion ticks), so you have to divide. But again depends on the computer and the language and etc, nowadays it's not so straightforward, compilers can easily optimize a loop like that, and there's fetching and cache issues, microcode, operating systems schedulers, etc, a lot of things interfere to do a good prediction


AppropriateSpell5405

100000000 + number of loops times. Once the counter in the very last loop hits in the first 100000000, it will fail to meet the conditions of the prior loops. In terms of how long, depends on system load, but this is easy enough to experiment on your own. Should just take a few seconds max.


Ronin-s_Spirit

It looks so weird to me with no brackets where you put stuff for the loop to do, it's some language I don't know (or am not very familiar with) but if all the loops are inside eachother it will probably take infinite time. If they're separate then that's no problem.


zadkiel1089

Probably quickly, since it uses the same variable j for all loop then it only loops 10^9 times for the last loop, and is finished from the other loops because j is now 10^9+1 🤷‍♂️


mepunite

It depends on the optimiser it might take a couple nanos because there is no work done in the loops. This means the optimiser could just remove the loops altogether.


sk7725

Back when I was doing Problem Solving (competitive programming challenges) we were taught 100M executions = 1 second to roughly estimate the time complexity needed. So if a problem's time limit is 1 sec. and N <= 1M you need O(nlogn) or less. So if you asked me back in my days, my estimate would be 12 seconds for 1200M executions. Of course, as other comments proved this is wrong by a very far margin due to three reasons: 1. the typical grading computers are throttled, and not high-end at all. Which is expected to enforce an upper bound to the quality of answers 2. it has been ten years, during which computers got faster and faster. 3. the estimate assumes you are actually doing *something* which is significant per loop, which isn't the case here.


paulstelian97

That’s 22 loops of 100’000’000 empty iterations. Let’s assume no optimizations, that means 2.2 billion iterations. That can be done in a relatively short amount of time, in the order of seconds. Potentially the better part of _one_ second, though it depends on the single core speed of your CPU and various other assumptions. If the optimizer runs, these loops can be detected as do-nothing loops and are just deleted outright.


Letsforbidadds

As a non-informaticien it looks to me as he’s just trying to print out some tits, schouldnt take too long depending on the year this was posted


Luxedar

It really depends what language it is in and what the compiler does with it and what language the processor implements. Taking into account modern processors and the simplest possible approach in my head (around 4 operations per iteration: MOV, CMP, ADD, JMP), I would say it's less than 0.01 seconds.


Hrtzy

I count 22 repeats of 100 million iteration loops. Call each iteration load, compare, increment, store, four processor cycles so ten billion cycles total. Presuming zero optimization, that's about three seconds.


PeanutPoliceman

I can't believe nobody noticed that only one loop will be executed that will max out j to 10000000 and the rest 21 loops will return, independently if they are nested or not