Lets compare the performance of c++ vs python counting to 1 Billion...Why is python so slow?
Жүктеу.....
Пікірлер: 3 200
@ProgThoughts Жыл бұрын
You can highly optimize the Python code by setting n = 1 billion before the loop begins.
@Nohomosapien
Жыл бұрын
Yeah and also the c++ one. But maybe he did that for a reason
@user-gw4jp3xg3n
Жыл бұрын
@@Nohomosapien bro really dodged the joke.
@Nohomosapien
Жыл бұрын
@@user-gw4jp3xg3n Oh yeah, can you make me understand the "joke"?
@blubaylon
Жыл бұрын
@@Nohomosapien the joke was that the whole point was to speed test it, not to actually have "1000000000" in the console. So it makes no sense to write n = 1 billion lol
@petrurk6835
Жыл бұрын
@@Nohomosapien are you that dumb bro
@lloyd26 Жыл бұрын
You see, Python is actually good since it gives you time to get a glass of water, do something, play a game, graduate and get a diploma, get a job, witness the year 3000, all while the compiler is doing its thing.
@budgethvick225
Жыл бұрын
Isnt python interpreted?
@lloyd26
Жыл бұрын
@@budgethvick225 It is.
@nvcbl
Жыл бұрын
@@budgethvick225 it gets compiled then interpreted
@sks2227
Жыл бұрын
@@nvcbl tru
@narrator589
Жыл бұрын
Python is not a compiler genius
@estrogeneral-intelligence5 ай бұрын
Fun fact: the -O2 flag on the gcc compiler will most likely optimize the C++ program to the point that the result is immediate…because it generates machine code that just puts the number 1,000,000,000 directly into the CPU register rather than actually counting anything. At least this is what happened when I tried it with plain C.
@bspringer
5 ай бұрын
Just make the variable volatile then
@kylecrane4376
4 ай бұрын
My first thought as well. The compiler will see that absolutely nothing is done with that value of (n) and simply remove the looping
@wumi2419
4 ай бұрын
Yeah, I was surprised when it did't happen.
@jingato
4 ай бұрын
set it from user input with cin
@marc_frank
4 ай бұрын
would that still happen if you printed every number to the console?
@jesse25358 ай бұрын
This is a great showcase of how much python has improved over the years, I mean this would probably not finish a few years ago.
@jasonscala5834
4 ай бұрын
😂😂😂😂😂😂😂😂
@ronald3836
4 ай бұрын
So a few years ago the fastest way to run this program was to first wait a few years.
@chadmwest
2 ай бұрын
Talk about looking on the bright side...
@cheatoffchannel6320
Ай бұрын
@@ronald3836 😂😂😂
@1zui Жыл бұрын
I am really surprised that Python was only about 50 times slower.
@TheBuilder
Жыл бұрын
I didn't enable any optimizations in the compiler
@ujin981
Жыл бұрын
c=2.432; p=112.447; p/c >>> 46.23643092105264
@douglas5097
Жыл бұрын
lol
@user-tq9bu6ki2h
Жыл бұрын
@@TheBuilder the only avalible optimisation is just to skip iterations and add billion at once. Compiling with optimisation flag will change nothing or will make the test meaningless, I think.
@TheBuilder
Жыл бұрын
there are so many that the compiler does a better job optimizing the code. with python its not an option but any language can be equally fast
@ethannelson8656 Жыл бұрын
I told one of my professors that python was probably the best language to learn about parallelism and concurrency. He looked like I just admitted to support dog fighting. I then told him that python was so slow and inefficient, you would be able to visibly see the time difference from running on multiple threads. He laughed.
@croma2068
Жыл бұрын
Every time I stand up for Python people look at me like I just quoted Hitler
@ethannelson8656
Жыл бұрын
@@croma2068 It does have some niche uses. And I honestly believe it should be taught to children instead of cursive. That being said, it is pretty slow. And when its not slow, its because its using some other language.
@TheBuilder
Жыл бұрын
there are issues with the design of the language but the speed is fine for what i use it for
@noornasri5753
Жыл бұрын
Python is honestly the best. Sure if you're working on a large product or in a competitive setting, you'll need Cpp, Java, or sometimes C. But languages are just syntax, after a while using a new language is just deciding on the best language for the task then a few google searches. Python has so many uses, not just for learning. It's very heavy in ml, has many useful libraries (graphing, numpy), and can do straight up magic compared to other languages. Whenever I want to automate or check something, I just open idle. Edit: people replying about the "magic" just being simple pseudocode, yes that's exactly right lol. In just a few seconds I can reformat data with nested dict/list comprehensions into a structure that would take a dozen lines in other languages. I know lots of the stuff are written in C/Cpp anyways, that's like saying go use assembly because everything ends up being like that anyways. My whole point is that python is extremely useful, obviously there's a time and place.
@Metruzanca
Жыл бұрын
@@noornasri5753 "straight up magic" aka it can do what other languages do in slightly shorter syntax but it by no means has an advantage over other languages library wise. The only reasons python is so heavily used are: 1. its installed by default on all major linux distros, so its a prime choice for automation without further setup on fresh boxes. 2. Due to its simple syntax, its been picked up by data scientists to use for ML, but mind you ALL the heavy lifting is done in C++ so you could easily take say javascript which is also very easy to use (and has equivalent packages for everything) but is also much faster (using this shitty benchmark, written in node I get performance thats just a few ms slowler than c++) Python is not the best, never will be. Its just a very conveniently placed language. Want a language that actually does magic that no other language can? Learn rust.
@cerulity32k7 ай бұрын
Tip: You can use underscores in Python to separate numbers. Example: 1_000_000_000
@Injinct
5 ай бұрын
thanks
@Zorcky-2C
4 ай бұрын
Wtf is notation!? That is so ugly
@living-in-ohio
4 ай бұрын
Aint spaces just better
@RedHair651
3 ай бұрын
It won't work @@living-in-ohio
@ieatthighs
3 ай бұрын
@@living-in-ohioaren't*
@MrEgorchikZ7 ай бұрын
The catch: it doesn't include compiler optimizations on C++ part. Otherwise it would probably turn into just "cout
@filipburcevski9566 Жыл бұрын
I once tried counting to 1 Billion in my head. It took me a few centuries. I am glad I finally finished with that.
@TheBuilder
Жыл бұрын
same tbh
@Clayne151
4 ай бұрын
Me too, but I optimized the loop und just thought of 1 billion.
@MrMeaty6
Ай бұрын
bro how slow where u counting`??? 1 bil seconds is 31 years
@mik8352
Ай бұрын
@@MrMeaty6 Well, @filipburcevski9566 is right because it's going to take you more than one second to name each number... So yeah, it's going to take a few centuries.
@marjensendk
Ай бұрын
try saying 555.555.555 in one second :)
@adrianprayoga335 Жыл бұрын
the semicolon in python is just perfect as someone who write in C++
@TheBuilder
Жыл бұрын
Muscle memory 💪
@listafe4938
Жыл бұрын
Also parentheses in the condition
@bobbyfeet2240
Жыл бұрын
I cut my teeth on C and only came to Python for work purposes target recently. I'm often told in coffee reviews that I'm getting "paren happy" in my conditionals and a few other places. Not so much an issue with semicolons, weirdly.
@usernamerequired788
Жыл бұрын
@@bobbyfeet2240 yeah. when I do python I’m like well why shouldn’t I use parentheses if it still works after I put them in
@AWriterWandering
Жыл бұрын
Funny thing is you can write semicolons in Python if you really want to. It basically just ignores them.
@mikuch_ws52514 ай бұрын
I had never delved into programming before, but this seemed so straightforward that I couldn't resist giving it a try. Using VS Code, I successfully executed it! Thank you; it was an enjoyable experience!
@TheBuilder
4 ай бұрын
Glad you enjoyed it
@mkapper9800
Ай бұрын
AI bot 😅
@tigrankhachatryan6119 Жыл бұрын
I'm actually planning to work on a Python-like compiled programming language soon. This video remotivated me. Thank you
@TheBuilder
Жыл бұрын
Golang or building your own?
@tigrankhachatryan6119
Жыл бұрын
@@TheBuilder My own, though I'm going to use LLVM as a backend because I don't want to lose my sanity. It's gonna support both high-level and low-level features. Also, it's gonna be gradually typed. I can tell you more about it if you want
@TheBuilder
Жыл бұрын
It's not something I'm familiar with. but if you want to share more you can contact me through email or join the discord
@RedHair651
3 ай бұрын
Nim?
@tigrankhachatryan6119
3 ай бұрын
@@RedHair651 Nim's not that Pythonic even though it's somewhat more humane than the average language
@richardhoyle8115 Жыл бұрын
Hey give Python a break! I bet you can't count to a billion that quickly!
@TheBuilder
Жыл бұрын
python does in 2minutes what it would take the average person a life time to do
@dekippiesip
Жыл бұрын
@@TheBuilder about 30 years if 1 second stands for 1 number.
@technolus5742
Жыл бұрын
@@dekippiesip and don't forget numbers get harder and longer to count as you go
@ProgThoughts
Жыл бұрын
@@technolus5742 Something else gets harder and longer
@GamingFrazix
Жыл бұрын
@@ProgThoughts yea- but he probably dosent have that so leave him alone lmao
@user-vi5vn1gm6p Жыл бұрын
I studied C++ and C# in university, but before that I was learning python (through online courses) for exam. Now it is funny to remember how teacher said that if we won’t optimise our code, it will calculate for longer than the exam lasts
@herseem
Жыл бұрын
When I was at university (ok, it was Thames Poly. It only became a university when I left), if you wanted to add a gigabyte of memory to your computer you'd first have to apply for planning permission to build an extension. Now, 32GB comes in those handly blister packs sometimes near the till for 'impulse purchases'.
@rickintexas1584
Жыл бұрын
@@herseem I know the feeling. I wrote my first programs in 1978 in high school. I wrote my first professional programs in Fortran in 1984 on a VAX computer shared by about 20 people. It only had about 256 MB of RAM to support all the users.
@AlexRodriguez-gb9ez
Жыл бұрын
@Game Plays 1230 Avoid dynamic features in inner loops, cache, use aggregate functions like the array functions in numpy since they are written in C and use vector instructions
@ilsignoredellaluce2234
7 ай бұрын
This is so true. I had to rewrite an entire program during an exam because the way i wrote It the first time was so slow that i couldn't reiterate it the number of times needed before running out of time
@user-rb9qm5wr2l
6 ай бұрын
Just had to make the thumbsup an even 1000.
@jormaig Жыл бұрын
You can get even faster c++ code if you enable optimizations with the -O2 flag. Although it's possible that the compiler optimizes the loop and removes it 😅
@TheBuilder
Жыл бұрын
that would be unfair since Python still dutifully does all those additions
@jormaig
Жыл бұрын
@@TheBuilder True although this also highlights the power of compiled languages that can optimise away unnecessary computation
@rb1471
Жыл бұрын
@@jormaig In python we call it optimizing away the software engineer
@alexanderd.7818
Жыл бұрын
There are ways to ensure that loop is not removed. #include #include #include uint32_t n; int main() { clock_t begin = clock(); volatile int deopt; for (n = 0; n != 1000000000; ++n) { (void) deopt; } clock_t end = clock(); double spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("%f ", spent); } 0.350250 with -O3, 0.98 with -O0.
@alexanderd.7818
Жыл бұрын
@@MTQvODg Hmmm… And how exactly would you suggest to benchmark it in a “good” way?
@ps_breakdowns Жыл бұрын
You can use an underscore as separator for intergers in python for better readability btw
@leaks1965
9 ай бұрын
but who needs readability in a 2 line file???
@LD-dt1sk Жыл бұрын
You might think that the major time difference was because he used different coding languages, but python would’ve been way faster if he just removed a few zeros.
@Superdeeep
Жыл бұрын
eaxtly and it would have been even more long for c++ if u added more zeroes
@weetabixharry
Жыл бұрын
These are the facts that they don't want you to know.
@jpsytaccount
Жыл бұрын
My question is, why not just set N = 999,999,999? Wouldn’t that speed things up?
@Superdeeep
Жыл бұрын
@@jpsytaccount what if and this is really genius. He puts it to 999,999,998
@ohneko6193
Жыл бұрын
How about we just remove the “1” and it’ll be infinitely faster
@silverasdf2055 Жыл бұрын
Sometimes you don’t need the program to run quickly. You just need it to run. That’s why I love Python. Although it’s certainly not the fastest language, its ease of use is great for beginners, and I can write a program quicker in Python than I can in c++. I don’t think I would be a programmer if Python didn’t exist, quite honestly. And keep in mind I love C++ too just for different reasons.
@user-wx1ns5hf3h
Жыл бұрын
You said everything right. However, there are people who are sure that there is only 1 language for all tasks in the world and that is python. I say this because I know a "hacker" who brutforce passwords in python (brutforce to find hash colision) and wondered why it took so long
@bljet4388
Жыл бұрын
Bruh tell us another thing everybody already knows
@ruynobrega6918
Жыл бұрын
@@user-wx1ns5hf3h you can use python for everything, as long as the libs are compiled in C lmao
@ruynobrega6918
Жыл бұрын
Jokes aside, the level of draft code you can make in python is unmatched by any other language. And honestly, for most stuff nowadays python is trully enough.
@factChecker01
Жыл бұрын
@@ruynobrega6918 That depends on the application. There are a lot of languages that are MUCH easier to use in particular applications. I have done a lot of scripting programs in Perl and it is much easier than Python for that. And MATLAB is much easier for many engineering applications.
@oes2546 Жыл бұрын
We're studying FEM/FEA by implementing it in Python code atm. And while it sits there forever using 26GB RAM and 96% CPU I think to myself, how fast would it be if written in C++? (Maybe it wouldn't be that bad of a difference since Numpy is written in C though. Idk really...) However, I wouldn't stand a chance to be able to implement the ideas/concepts we are using it for in such a short time if it was written in C++... It would at least double if not triple the time spent on the project is my guess 😅 Off course such an application would be implemented in C++ for an actual program. But each tool has its place. For us it is having an easy language, in order to learn FEA by implementing it in code, the coding part being secondary to the concepts we're coding at least within the course we're taking. That's where python shines I guess. It minimizes "barrier" between the scientific/engineering concept and the code implentation, and it's a great language for just that reason. Different tools for different purposes.
@MajinSaha
Жыл бұрын
If "the coding part is secondary to concepts", then MATLAB/Octave beat Python in that regard. Yet it's Python that gets all the f*ing praise smh.
@mujtabaalam5907
7 ай бұрын
@@MajinSahaMathematica is better
@piotrc966
4 ай бұрын
"the coding part being secondary to the concepts" always code is the second. It doesn't matter what you're doing whether it's a store or business rules in DDD or a game. In our company, we model the business in DDD using C#. (python is too slow and has poor objectivity - only by convention).
@Salzui
Ай бұрын
Did you consider using PyPy if applicable?
@eeshandev5081
26 күн бұрын
C++ and Fortran are best if you're solving CFD or FEA problems because as far as I know, C++ and Fortran are fastest when handling multidimensional array. OpenFOAM has its entire library written in C++ and is a great open source CFD solver.
@TheSwordfish269 Жыл бұрын
Thank you for this video!
@TheBuilder
Жыл бұрын
You bet!
@botondhorvath1445 Жыл бұрын
Please turn on -O2/-O3 in c++ the time will be mesured in miliseconds (There will be no loop...)
@morgard211
Жыл бұрын
Is there a reason why that's not done on default? How would the assembly code look like? Would it just be an add instruction bilion times? Wouldn't that binary be absurdly large?
@TheBuilder
Жыл бұрын
@@morgard211 sometimes optimization gets in the way of debugging so its an option. Enabling optimizations would probably result in the compiler computing the loop at compile time and giving you a binary that just prints the value
@chri-k
Жыл бұрын
@@morgard211 also optimization is not perfect and sometimes breaks functionality in complex programs, requiring additional time to figure out what the optimized did and how to tell it to not do that.
@mmyd2405
Жыл бұрын
@@morgard211 Assembly is also capable of loops bro (jumps/calls) So about 5 lines are enough for this (if you actually loop through it unoptimized) If you Compile on -O3 the compiler would register the loops and set the variable to 1000000 instantly instead of adding 1000000 times
@botondhorvath1445
Жыл бұрын
@@chri-k Optimalization only breaks code if there is UB in it. (Assumeing that you have a good compiler) If it breaks a complex program then that is because someone wrote a wrong code somewhere in it. But if the faulty code is in a wrong place, then it is extreamly hard to figure out how to fix it, maybe harder than it worth.
@doomknight233 Жыл бұрын
Python enjoyers: NOOOOOO you're not doing it right. Rust enjoyers: Let me try my best to show why Rust is faster than C++ than this video does, and why it should be the best! C++ Enjoyers: I wonder which libraries written in C++ they're going to use...
@Longus07
Жыл бұрын
As far as I know most of the libraries used by python or rust are written in c not c++ Edit: just to clarify rust mostly uses libraries written in rust but there still are a lot of c libraries which are used in rust mostly because they are already high performance, well established and we'll documented.
@shengalabu8050
Жыл бұрын
@@Longus07 isn't c also c++ cuz if you run c code in c++ it'll still work so technically all c code is c++ but weaker
@Longus07
Жыл бұрын
@@shengalabu8050 NO
@Longus07
Жыл бұрын
@@shengalabu8050 most of Java code will run in c# excluding the libraries and imports
@shengalabu8050
Жыл бұрын
@@Longus07bruh why you talking bout java?
@HypherNet Жыл бұрын
It would be really nice to include javascript timings. On my machine: C++ is 0.66s, Python is 42.37, and JS (Node) is (amazingly) 0.53s. Presumably V8 is doing some crazy optimization, so I added a Math.random() check in the loop, and it went up to 6.3 seconds. Still very impressive.
@nvcbl
Жыл бұрын
nodejs is now the god of all languages
@youtubedeletedmyaccountlma2263
Жыл бұрын
@@nvcbl nah is not. I hate nodejs
@fabricebalan
Жыл бұрын
there is something wrong with your c++ compiler or computer then
@TheForge47
Жыл бұрын
@@nvcbl lul this pice of shut up mark and Go away
@diegocantelli
Жыл бұрын
Ricky, i don’t know…
@nexpro69852 ай бұрын
Can we get a demonstration of how long it takes to write and debug some c++ data processing tasks that python can do in one line of code?
@ThatOpinionIsWrong Жыл бұрын
Isn't For Loop like twice as fast compared to While Loop in Python? C++ would still obviously win but I believe Python's score would look better.
@TheBuilder
Жыл бұрын
Using the Numba library can make Python comparable to other languages for simple operations.
@unknown3158
Жыл бұрын
@@TheBuilder Yes, with JIT. Doesn’t work for everything though.
@royler8848
Жыл бұрын
@@TheBuilder it's not even that, the range psudo iterator is implemented in c, not in python. You spend much more time running c code when using range compared to a manual while loop
@Eknoma
Жыл бұрын
Pythons for loop is like 5 times slower than while, as it basically uses a while loop, but also try/except, which majorly slows it down
@moneymouse
Жыл бұрын
@@Eknoma kzread.info/dash/bejne/g5uZ2NtwZcbVaMY.html No it is not
@Killerkraft975 Жыл бұрын
To be honest, Python was my first language to then go on to Java, C and C++. Its very good to learn with very high level and general programming but when you dig deeper, it falls short except from certain tasks like machine learning.
@TheBuilder
Жыл бұрын
Similar story with me, except I started with C, switched to Python and thought it was the best thing ever since I could write 5 lines of code to do practical things....then I started working and realized lacking a strict type system makes Python and JavaScript prone to errors especially on larger projects
@sepxviii731
Жыл бұрын
Machine learning in python is done in C...
@dtikvxcdgjbv7975
Жыл бұрын
@@sepxviii731 good one 😂👍
@sepxviii731
Жыл бұрын
@Tarik B. try Julia
@sepxviii731
Жыл бұрын
@Tarik B. You live in the past century. Julia sometimes is even faster than C
@AshleyNewson7 ай бұрын
If optimisations were enabled (even -O1), any decent C++ compiler (such as Clang++) would replace your entire program with `std::cout
@kris.yochev7 ай бұрын
If you use -O2 or higher, the C++ loop gets folded completely, making it even faster
@ChrisM541
6 ай бұрын
You mean unrolled?
@vladimirarnost8020
6 ай бұрын
@@ChrisM541No, he means replaced with a precomputed constant, i.e. 1000000000.
@ChrisM541
6 ай бұрын
@@vladimirarnost8020 Thanks, that's interesting. Is there ever a danger this type of 'optimisation' happens in the wrong situation?...where it is absolutely not wanted?
@vladimirarnost8020
6 ай бұрын
@@ChrisM541 Good question. The compiler is usually doing a good job not breaking code by over-optimising it. However, when the goal of such a loop is to wait for a certain amount of time, e.g. in embedded code touching hardware directly, the loop removal might break such code as it would simply run too fast.
@NikPower-gs6hs
5 ай бұрын
@@vladimirarnost8020you can specify if functions or certain code parts get optimized or not just for that purpose
@jrwkc Жыл бұрын
But there is a package for that import counting_library, speed speed(counting_library.count(100000000))
@xCwieCHRISx
2 ай бұрын
and good packages are written in C 😁, like numpy. Python is just a powerful API for C libraries.
@christianm4906 Жыл бұрын
Now process data on each iteration and you'll see how python performance decreases dramatically. Depending of the case I've noticed that python is a about 500× slower. For example try calling a method within a custom class.
@christianm4906
Жыл бұрын
@@ILubBLOfficial that's OK. However not everything can be run with those libraries. I'd prefer integrating python with C++ using a wrapper such as Pybind11, SIP, shivoken, boost::python, etc . That approach for optimisation is much more powerful as it brings the best of python and C/C++ together. By the way, Numpy is a descent approach. However Eigen which is the C++ counterpart is much faster and optimised. Pandas is a huge package. Too many things there that aren't always necessary.
@christianm4906
Жыл бұрын
@@themystic5935 realistically speaking. Many companies specially in embedded systems, prototype in python and rewrite everything in C/C++ for production. I still consider that Python and C++ work fine together. They are just tools not religion.
@christianm4906
Жыл бұрын
@@ILubBLOfficial Eigen which is the C++ equivalent to numpy is about 20 or 30 times faster than numpy. And also, not always you can avoid Python bottlenecks. However I don't critice Python for that. I think it is still a great scripting tool for a range of applications. What I critice is that there seems to emerge a new generation of developers, most of them beginners that frenetically love a specific programming language as if it were a sort of religion. They wrongly think they can do everything in a single programming language and they don't admit the weaknesses of their favourite tool. They are just tools, not religious. There are also many areas in which Python is a better choice than other tools, but when it comes to optimisation, performance, and concurrency, Python performs very poorly. Probably worst than the vast majority of its competitors, and that's why it is recommended to learn more than just python.
@AlexRodriguez-gb9ez
Жыл бұрын
@@christianm4906 Where did you get your statistics from. From what I see its more like 2-15x slower.
@MrPyach2 ай бұрын
Don't you think c plus plus compiler removed effectively empty cycle from assembly code?
@dewiz9596 Жыл бұрын
I had my “road to Damascus” moment in 1981 when I wrote and ran a similar routine on the Original IBM PC. . . first, interpreted BASIC, then Compiled BASIC, then in C. I was showing my kids. Well, I was blown away. Even though I had written some “pretty good” code (worth about $1,000,000) for my employer, I NEVERwrote another line in BASIC.
@wrmusic8736
5 ай бұрын
My first programming experience was with ZX Basic. Speccy allowed to do Assembly (or rather literal machine code) by "poking" memory (e.g. storing literal values in it and then calling a desired memory address to execute), but sadly my child brain couldn't comprehend it. Basic was slow of course and I had to scratch my head trying to understand how all the other programs ran so fast for a while. At some point I learned there was a C editor, but I couldn't find the tape anywhere.
@sustrackpointus8613 Жыл бұрын
For loop in python is faster than while, should use first one
@TheBuilder
Жыл бұрын
It's faster but not by much
@rivercape982
Ай бұрын
@@TheBuilderit is much faster, around double
@Jp-ue8xz
Ай бұрын
@@TheBuilder uhh... "from numba import jit". Wrap counter in function with decorator @jit(looplift=True). Same operation takes just well under 1s
@0xN1nja Жыл бұрын
0:28 I KNEW IT 😂
@TheBuilder
Жыл бұрын
Python is actually faster if you ignore the numbers
@AMindInOverdrive7 ай бұрын
A simple but effective example for sure!
@user-qr4jf4tv2x8 ай бұрын
so glad i started learning c++ again after doing javascript and now also learning rust
@swiftz6098 Жыл бұрын
You can get the time down to 25.8 seconds using a for loop instead of a while loop in python.
@swiftz6098
Жыл бұрын
I lied, that was without printing the number. for loops are still faster though.
@furkanunsal5814
Жыл бұрын
@@swiftz6098 well, that is absurd.
@wrnlb666
Жыл бұрын
he can also make the C++ Program about 4 times faster using register int n
@arthur1112132
Жыл бұрын
@@wrnlb666 the compiler should automatically do that tho
@wrnlb666
Жыл бұрын
@@arthur1112132 But it's c/c++, so the compiler gives you the power to choose if you, the creater of your own code, want to let the compiler do that or not.
@huutuan209 Жыл бұрын
You really added a semicolon in Python 😂
@SamMcPieVTOL
Жыл бұрын
Python enjoyers be like: oh my gosh you added STRUCTURE and READABILITY to your code?? lol lmao wtf is that what are you?? A loser????
@Morimove
Жыл бұрын
this is called muscle memory 😂
@TheBuilder
Жыл бұрын
subconscious bias
@jojo989GD4 ай бұрын
why did you used size_t instead of int? sorry for that nooby question, it seems curious for me :p
@hedgeearthridge68072 ай бұрын
I ran it in Common Lisp and Racket (translated by ChatGPT because I still suck at them) on Linux Mint with a 5600x CPU: - Python took 39 seconds. - CLisp using SBCL took 0.222 seconds. - I gave up on GNU Clisp after 6 minutes. - Racket took 0.845 seconds. I altered them to print the results to make sure they actually did the task, and they printed one billion. The Racket script is relatively complicated and might not be optimized well. But these results are crazy!
@alwayslg Жыл бұрын
I think there’s some settings you can tweak for cout speeds. I saw it at an article wrote by geeks for geeks or something it’s about competitive coding
@hi-tk4hu
Жыл бұрын
Yes n +=1 is faster than n =n+1 for some reason
@mactalk2871
Жыл бұрын
@@mb_entity cout is called every time there is a iirc, maybe im mising it up with printf
@04ZFZ
Жыл бұрын
Iirc it's cin.tie(0); sync_with_stdio(false);
@unknown3158
Жыл бұрын
@@mb_entity You are not dumb, you are actually correct.
@alwayslg
Жыл бұрын
@@04ZFZ I think this is it
@seasong765510 ай бұрын
I've just tried this with pypy: c++ 1.04s python 40.21s pypy 1.01s
@xEndless11
3 ай бұрын
wow nice! I didn't even know there was something even faster, i will figured out ^^
@thecheesybagel8589
2 ай бұрын
this is because the back-end of python in written in C. you can get the python interpreter to loop in C rather than in python
@felixmarshall8614
Ай бұрын
@@thecheesybagel8589 exactly. It was strange for me to watch speed competitions when the developer did not use all the capabilities of Python for this
@PatrykGlogowski
Ай бұрын
@@felixmarshall8614 he also dont use capabilities of c++ -o2
@godofclash25173 ай бұрын
I didn't see printed char on console. How we can check this two examples are equivalent?
@hess29067 ай бұрын
A modern compiler such as the GNU C++ compiler you use in the video, do many passes and optimisations. There is a possibility the compiler may have changed the code to something other than 1 billion increment instructions that would make this comparison fair. However the point still stands that python will always be much slower for operations like this; it's not the right tool for this job, just as you wouldn't use a screwdriver to punch a nail into a wall, though the screwdriver has uses of it's own
@TheBuilder
6 ай бұрын
Optimizations were turned off in the compiler, counting up to a billion actually takes a second or two on most processors
@perfectketchup Жыл бұрын
2.5s is excessively high, whats your CPU? I get ~250 ms on C# JIT optimized, ~750 ms on unoptimized with Ryzen 7 Laptop CPU
@eherlitz
4 ай бұрын
Got 290 ms on c# compiled for release and run on a linux laptop with a Xeon E-2286M CPU.
@Jp-ue8xz
Ай бұрын
IF I run this raw C with no optimization flags in my asus potatobook from 2016, then I get similar times as this guy. But just using -O2 flag drops it to less than 10ms. It's an incredibly weird "flex" anyway considering python also takes well under a second to do this if you wrap the thing in a function and use a JIT compiler
@KanashimiMusic Жыл бұрын
Okay seriously how can you live with a tab width of EIGHT? And also why do you have different tab sizes for C++ and Python?
@SkySentry7
3 ай бұрын
mine is 2😂
@Valentyn007
Ай бұрын
Mine is -1 😁
@SkySentry7
Ай бұрын
@@Valentyn007 🗿
@KanashimiMusic
Ай бұрын
@@SkySentry7 While I personally don't like 2, I think it's tolerable at the very least lmao
@KanashimiMusic
Ай бұрын
@@Valentyn007 giga based
@michaegi4717 Жыл бұрын
Perfect example, why there are optimized languages for different usecases. This comparison is like compare a kitchen knife and a leatherman by chopping onions with both.... or by turning a screw into wood with both.
@aaronsteers5 ай бұрын
What this example misses is the fact that most "python" libraries actually are built on top of C++ and/or Rust for the heavy lifting. If you are writing Python that doesn't delegate processing to another library, you're doing it wrong. You can't conflate Python as a language choice with examples like these that no one would/should actually implement.
@samuelluc1324 ай бұрын
Dude it takes 341 milliseconds for nodejs on my machine. On what pre-world war machine are you running your C++ code for it to be so slow?
@TheBuilder
4 ай бұрын
Turn off optimizations
@codycast4 ай бұрын
Can someone explain this to a non-programmer? Wouldn’t the code to the CPU’s be the same? Don’t compilers, even if they’re being done in real time, change the code into assembly instructions for the processor? I would assume that such a simple program would result in the same instructions being seen by the CPU.
@tholod
Ай бұрын
I know I am two months late to answer, but I think your question is interesting. Your mistake is to considered Python as a « compiled at runtime » language, which is not true. Compiled language are transformed to CPU instructions during compilation as you seem to know. Python is an interprated language, that means for each code line, the python program (python.exe or /bin/python) reads the line (reading a string is a set of CPU instructions), and updates its state in memory according to the python code. It is like there is a layer between CPU and code, the python code will never be translated into instructions. The python program is for python what the CPU is for C/C++ language : the executor. However the python program is made of CPU instructions,and running it to execute the code line takes CPU time to execute. The same applies to CPU, you can have an algorithm done with instructions that runs on a CPU, but you can also design a chip that is specified to do this same algorithm and it will be quite faster than the CPU (if it is well-designed) because there is one layer less (there is no more instructions that translates the algorithm). However you lose the versatility of a CPU which can execute different algorithms. It is the same with python, it is a language where programs can be run and debugged fastly because there is no compilation time, but with less efficiency than compiled language (some tools try to avoid that by compiling python code at runtime like Numba and get better performances).
@ADEpoch3 ай бұрын
So how do they compare with for loops instead of while loops?
@prateek16 Жыл бұрын
Does that mean python is very slow as compared to c in running big blocks of code ?
@TheBuilder
Жыл бұрын
I think Python is faster than C when I want to get something practical done
@captainswing4040
Жыл бұрын
@@TheBuilder python is a great scripting language with enrmous support but it has a purpose and that is not same as that of C
@jebbi2570
Жыл бұрын
@@TheBuilder But it quickly become slow when the project evolves.
@taihuynhuc3135
Жыл бұрын
@@jebbi2570 How much your project will evolve anyway? Actually many softwares out there dont need to evolve that much.
@corex6109
Жыл бұрын
@@jebbi2570 The great thing about Python is that whenever you truly want/need C's speed, you can just write a shared library providing that functionality in C, then call it from Python. Of course this too has its limits, but it's a nice workaround for when there's one significant bottleneck.
@itdw5942 Жыл бұрын
for best optimization you can set n to 1 billion and use a prefix decrement inside the condition
@codingjq
7 ай бұрын
I thought gcc turns i++ into ++i automatically?
@benr9914Ай бұрын
I want to see the compiled code to see if the compiler is able to optimize the loop out.
@azkh6945 ай бұрын
Python code’s 1st execution is also its compiling stage. On the 2nd run, it is way faster. You should have either calculated c++ compiling time + run time or compare python’s 2nd run
@sinoichi
4 ай бұрын
Python does not compile anything... it's interpreted language. Second faster run it's just cache layer, but it's only temporary :)
@catfan5618
4 ай бұрын
@@sinoichiWrong, it compiles the code into byte code which then gets interpreted.
@sinoichi
4 ай бұрын
@@catfan5618 Then you wouldn't need python installed. 😉 Sorry, python scripts are executed line by line by python interpreter.
@sinoichi
4 ай бұрын
@@catfan5618 And if you think it is compiled. So where does the binarie goes? Where is executable file? Because when you run python script it does not change it's form. It's still editable. Even if it would be compiled to RAM, there is no sense to not get compiled files.
@TheThilor
4 ай бұрын
@@sinoichi Compiled does not mean we get a binary. See Java, we compile our Code, but dont get a binary. Python compiles it code into bytecode and stores this into .pyc files.
@1over137 Жыл бұрын
I actually came across this recently. I was trying out micro-python for the first time on an RP2040 Rasberry Pi PIco W. The embedded version of "Hello world" is "Blinky", you blink the LED on and off. Wow! I figured out the gpio library, but I couldn't bother to find the "Delay" function/method/module, so just counted to 100,000. I was expecting to have to ramp that up much higher and thankful I didn't need to think about datatype in python.... but no. The LED blinked with about 1Hz frequency. counting to 100,000 took 500ms! To be honest I haven't switched it back on again. I don't think it's the RP2040's fault, I think it's python's fault. If I did that in C on the same board the LED would just look a little dim and flickery. If I did it in ASM it would just look like it was on.
@asuasuasu
Жыл бұрын
"counting up to a number" is a very bad baseline for comparisons. For one, these languages have extremely different performance characteristics. (Micro)Python is naively interpreted. It absolutely doesn't have advanced optimization passes that would make it able to reason about this. A C++ compiler will be able to make sense of your counting, and is likely to trash away your loop, 1. because it'd be able to figure out that you're just counting up to 100000, and 2. because you're probably not even using the value... so it can just optimize it away entirely. Though, if you need anything reasonably fast then MicroPython is not a good idea, for sure. I heavily use Python and I dislike the idea of using Python in embedded programming. Assembly is not a magic bullet. If you know your C/C++ and optimization, then dropping down to assembly is rather unlikely to let you write faster code.
@jackroutledge352
Жыл бұрын
Bear in mind that the raspberry pi foundation's goal is to teach people programming. Python is their standard language for everything they do (hence raspberry "pi"), because it's easy to learn. Having said that, you can program the pico in cpp as well.
@qwertykeyboard5901
7 ай бұрын
Ported an NQUEENS algorithm to both J2ME (SPH-M330) and an arduino (ATMEGA328P). The arduino was ~20% faster. Arduino UNO clones usually clock the ATMEGA328P at 16Mhz. The Samsung has a full 32bit ARM processor at (probably) 192Mhz. It might even utilize the "jazelle" instruction set. Thats honestly really fucking pathetic for Java. Needless to say, I was incredibly pleased to find out that my stupid conway GOL demo ported to C (Qualcomm BREW) was so fast that blinkers are a blur on screen.
@Insanit13s Жыл бұрын
I was curious to get the times on my machine. C : 1s740 Python: 47s Perl: 34s
@MrKrzysiek9991
Жыл бұрын
JS ~2.0 sec
@rodrigozayit
Жыл бұрын
java 0.025s
@ricardoangelesgomez8667
4 ай бұрын
Python on PyPy: 1.083s
@nathanwhite704 Жыл бұрын
Was this comparing just the initial compile times or the finished program? How did the c++ do 2.4 seconds? I ran the same thing in visual studio 15 minutes ago and it's still counting. You must have a beast of a workstation or I messed up somewhere.
@TheBuilder
Жыл бұрын
are you printing every single number?
@nathanwhite704
Жыл бұрын
@@TheBuilder yes.
@TheBuilder
Жыл бұрын
@@nathanwhite704 there's your problem
@violetsnowflakes5 ай бұрын
That's very odd. I just ran it now, and Python was faster than C(though not CPP), but it was both just above 1 second.
@fbiagentmiyakohoshino8223 Жыл бұрын
time to do this in other languages like lua, javascript and csharp
@gazzalifahim Жыл бұрын
How do you show the time required like Real, User, System etc? Seems So cool 😀
@glidersuzuki5572
Жыл бұрын
That's the 'time' application he uses at beginning. Usage is as follows: time
@gazzalifahim
Жыл бұрын
@@glidersuzuki5572 Thanks a lot. 💯
@TheBuilder
Жыл бұрын
this
@bobuccman1424
Жыл бұрын
windows user when encountering built in unix commands be like
@GraceKeyz2 ай бұрын
Would like to see an int wrapped in an object for another comparison.
@DanKxxx Жыл бұрын
while loops in python are terrible for performance if you are iterating many times. In reality you mainly use python for data and simple codes where you import libraries written in c and c++ which make it perform just as quick as low level languages. If you want to build anything big that isn't easily avaliable via a library you use a low level language, for simple quick things like data analysis python is pretty nice to use.
@TheBuilder
Жыл бұрын
yes
@aaronsteers
5 ай бұрын
Exactly. The reason Python ISN'T slow is because good python code handles control-of-flow in Python and heavy processing in another service. What you lose in raw power in higher-level language, you can gain back 10x in better design and maintainability overall, if you're doing it right. You can't imagine how many times I've seen code that can't be optimized because it's too convoluted and not enough people are actually able to contribute the obvious fixes that are needed.
@Hooverdreng Жыл бұрын
Nice comparrison. However I think a lot of people are a bit too invested in efficient code. In many environments, computation time is much less expensive than coding time. So if you only have to solve a given task once or a few times, the computation cost is easily mitigated by the saving in coding time.
@sitting_nut
Жыл бұрын
Why do you think python coding time less than c++ coding time? maybe true about c if one codes from scratch (instead of including libraries) for say data structures etc. but definitely not true about c++.
@Hooverdreng
Жыл бұрын
@@sitting_nut I can’t speak for all disciplines. I am doing data analysis and measurement and control for experimental physics. And for that purpose Python is the faster and more flexible option. Could I write the same thing in C++ and have it be faster? Sure. But I don’t need to and using python my code will also be more accessible to people following up on my work. I don’t need an F1 car that only the cool kids know how to drive. I need a Ford that benefits more people.
@sitting_nut
Жыл бұрын
@@Hooverdreng iow you are supporting your bias with personal anecdotes instead of objective data (and say all that unironically while you are saying your work is about data analysis, measurement, and experimental physics). anyway, once again my point was that your claim in op, that there is a coding time increase for using c++ over python, is false. that point had nothing to do with f1 cars used as metaphors.
@cagefury3789
Жыл бұрын
@@sitting_nut Seriously? Idk, maybe he got that impression with a simple hello world? lol. In c++ you have to import/include a std library, use a bitshift operator and put it in a main function. In python you type "print".
@sitting_nut
Жыл бұрын
@@cagefury3789 if you know anything, you know you don't actually need to include std lib or io. and why do you need a bitshift operator in hello world? fact that you had to make up such absurdities to make your claim, indicate even you , ignorant as you obviously are , know that, claim there is a coding time increase for using c++ over python, is false. typically you pretend you don't know python scripting mostly consist in importing other libraries. and how is " "__name__ == “__main__”" , and other such nonsense to structure any significant program , an improvement on main function in c++?
@puppergump4117 Жыл бұрын
By the way, these types of loops would normally just be optimized to print out 1 billion from the start.
@Hephasto
Жыл бұрын
I’d love to see C and assembly for comparison. But not shitty count, something more realistic
@petrjara7559
Жыл бұрын
@@Hephasto Nowadays if you use some better C compiler it generates like 95% perfect asm code. For "more realistic" = more complicated programs it's even faster to write in C unless you REALLY know how to optimize in assembly just because there is already 50 years of optimization experiences in the compiler
@donovan6320
Жыл бұрын
But that would have taken less than a millisecond.
@puppergump4117
Жыл бұрын
@@donovan6320 You can try it, just do the same loop but compile with the /02 or /03 flag. It won't compute values that aren't read. Now a better way to test how quickly a computer can increment would be to start a timer and use some time limit as the condition to exit the loop. The result should be in the hundreds of millions per second, but I'll test it myself in a sec
@donovan6320
Жыл бұрын
@@puppergump4117 I can too lol, would do it
@johnflare59256 ай бұрын
What shell are you using here?
@sanartvideos3 ай бұрын
I got the same result in C and Python using huge random complex tasking with optimized code in Cython / CPython and better results with Pytorch. Python provides me interpreted and compiled worlds with simple code and few hours of programming.
@PrimeToolbox Жыл бұрын
That's a important trade off. Does anyone here have experimented compiling Python code with Cython or Numba? I wonder how it will perform in this situation. Also, now with Python 3.11 it got a bit faster. But still much slower than Cpp off course.
@spartanbirdz
Жыл бұрын
3.11 version made it 15% slower for me lol.
@agalliazzo
Жыл бұрын
Just tested in a RPi4: - Python 3.9 + Numba 2.257s - C++: 6.052 I, honestly, was not expecting this...
@marcotroster8247
Жыл бұрын
Numba needs to JIT compile your loop. It converts the code into C and compiles it on-the-fly. That's why the first execution is slow. If you use the function a lot, it's as fast as C. And it's even smart enough to put your vectorizable code onto the GPU without you noticing, it's crazy good 😂
@agalliazzo
Жыл бұрын
@@marcotroster8247 Really I was not expecting that with numba the time is about 1/3 of a plain c++ loop... I was expecting something similiar in performance, so 6s about...
@marcotroster8247
Жыл бұрын
@@agalliazzo Numba is really good at vectorizing loops 😂 I suppose it's doing multiple additions at once with SIMD optimizations or GPU 😎
@nolanfaught6974 Жыл бұрын
You can make the C++ run even faster by using printf() instead of std::cout. I managed to reduce the speed to 50ms with just that change
@target844
Жыл бұрын
That is not the difference. You change is because of what optimization the compiler did. I god 30 microsecond for the code above and -O3 optimization. The compiler realise the final value of n do not depend on anything unknown at the time of compilation and can just set it to the final value and remove the while part completely. Test to add volatile as a keyword to n or test both print methods in the same compiler
@nolanfaught6974
Жыл бұрын
@@target844 Good catch, execution time was significantly slower once I used volatile. I've had bad experiences with std::cout in the past, to the point where almost 1/3 of my execution time was spent on basic I/O. A rewrote the backend to use `printf` and performance increased quite a bit.
@skotch_izolentovich3 ай бұрын
Whe do you use postincrement? Isn't it more effective to use preincrement?
@viper_0097
3 ай бұрын
compiler can optimize that if using postincrement have not difference with preincrement
@notalexbaker49595 ай бұрын
I’m new to programming. I’ve been learning intro python. Can someone explain why the languages have such different processing speed?
@TheBuilder
5 ай бұрын
every data type in Python is a lot more complicated compared to C or C++, for example, every time you interact with a number in Python, the program will call various other functions while in C or C++ the operation is only a few assembly instructions
@pnachtwey Жыл бұрын
C++ has the advantage of using register variables. That reduces variable memory accesses to zero while in the loop. Python must push and pop n on and off the stack.
@blip666
Жыл бұрын
How do you know this ?
@purdysanchez
Жыл бұрын
I too would like to see more info, but it's a pretty plausible explanation.
@ctleans6326
Жыл бұрын
@@blip666 Compiler explorer can show the assembly output of compiled programs and you can see it directly interacting with cpu registers (eax, edx, etc.). Cpu registers are far faster than memory accesses. I don't use python so I don't know how it works internally but it's physically impossible for a language to optimize with cpu registers without compiling to binary. There are way more reasons why c/cpp/rs are magnitudes faster than python. 1, yes, it is a compiled language so any "actions" are just one instruction to the cpu. 2 Static typing also makes it faster because memory is constant size and no need for extra memory to store types. 3. Static typing and other restrictions allow optimizing compilers, esp. llvm to analyze data flow and other stuff to inline/remove/optimize assembly. 4. garbage collectors do add overhead to the code, i don't think by much but languages without gc, especially rust, know exactly what parts of memory to deallocate.
@Fl4shback
Жыл бұрын
I would expect the compiler to just optimize the loop away and set the value to 1 billion...
@DemonixTB
Жыл бұрын
@@Fl4shback it would do that if any optimizations were enabled for the compilation in the video, the author said in another comment that it felt unfair to do since python cant do that, lol
@cycv5881 Жыл бұрын
True story, my friend and I went to a coding interview where they treated all languages the same and had a run-time limit. We both got the question, I used python w/ DP, he used C w/ brute force :)
@firstlast9813
10 ай бұрын
Dang! Brute force? 😂
@8BitGamerYT1
8 ай бұрын
And who did better
@howabout2138
18 күн бұрын
@@8BitGamerYT1the Python probably still runs and c brute force finished before guy fully lifted finger off enter
@alexeynaidiuk399 Жыл бұрын
use for loop instead in python. for loops is basically written in c in cpython implementation, must to be faster than while statement
@linux24207 ай бұрын
I thing gcc has some optimisations enabled by default. Is this also the same result without optimisations? It could just be that the compiler sees what the code is doing and simply sets n to a billion right off the bat
@ItsCOMMANDer_
4 ай бұрын
Only with "-On" flag where "n" is the optimisation level, with n >= 2 the for loop will be removed, below thta, nothing willl change
@JustAPersonalUseBarb7 ай бұрын
The cool thing about python is that there are so many ways to optimize things. Basic code like this may be really slow, but there are ways to 100x things like this
@uniquetobin4real
7 ай бұрын
Thats why i hate python... Never straight there are a billion ways to do the same thing, fkn snake 😂
@Pekara121
6 ай бұрын
@@uniquetobin4realthis person really said "it's cool when things are complicated and not simple 😃" like what?? 😂
@F14_Tomcatter
5 ай бұрын
Such thing is seems near impossible in this simple scenario, demonstrate it if you think that you are true.
@EWILD99
4 ай бұрын
@@F14_Tomcatter the fact that the code runs in about 4 seconds when you run it not 1 minute because he ran a precompiled C file, but the python file wasnt so it compiled then ran. if you run it a second time it is about 4 seconds as tested
@MrRjizz
4 ай бұрын
@@EWILD99 i remember implementing the dutch flag problem for large suffix arrays for a algorithm course i had and running one large sample set that would take like 3.0s on java would take the python code like a hour.
@PUNCHLER Жыл бұрын
I think if you use -o2 while compiling c++ it will be more optimized
@uwirl4338
Жыл бұрын
Unlikely to make a huge difference in this simple of a program
@wrnlb666
Жыл бұрын
@@uwirl4338 no, with O2 optimization, the compiler will just set n to 1 billion before the while loop. To truly optimize the code, he can add a register keyword when declaring n, that will make the program runs 4 times faster on my pc
@taragnor
Жыл бұрын
@@wrnlb666 Oh really? I was under the impression the register keyword didn't even really do much on modern C/C++ compilers and was more a relic of the past, since modern compilers are so much better at optimizing now.
@target844
Жыл бұрын
@@uwirl4338 -O2 will make an enormous difference. The optimizer can and will realize that the end value of n does not depend on anything unknow at he time of complication that can change so it can be precalculated. If you look at the generated assembly -O2 will eliminate the loop completely. I tested the code on godbolt with the option and -O0 takes 3 seconds compared to -O2 at 30 microseconds. It is an optimization of a factor of 100,000, so an enormous difference. That is a runtime measure in the program around all of the code shown in the video so any startup time is not included. If iI ht optimized variant measure time to before the value is printed the time I get is 0 µs. So the 30 microseconds is the time to print the result. If you add the volatile keyword for n it can be optimized away and you get 3s gain regardless of -O0 or -O2.
@wrnlb666
Жыл бұрын
@@taragnor compiler optimization optimize things that doesn't make the result looks different. In this case, setting n to 1 billion before the while loop doesn't make the result different. Because n is not volatile, and the compiler knows that it will not be changed outside of the program.
@rode_atharva4 ай бұрын
Bro which code editor you are using? Please tell me😮.
@tienbui2814
2 ай бұрын
It’s vim
@BnORailFan6 ай бұрын
As a software engineer for the past 35 years I have found that the different computer languages are a tradeoff of speed of writing the program versus the speed of running the program. Interpreted languages like Python are great for quick and dirty one-time programs but you wouldn't want to write a Python program that mines Bitcoins.
@chloe-un9cn
4 ай бұрын
personally i wouldnt want to write any program that mines bitcoins
@MarcioWesleyBorges8 ай бұрын
Addendum: For some machines, C/C++ simple loops as shown are more fast if you add one or more (try it yourself) "nop" instruction into the loop. It may appear bizarre but can be easily explained: because the instructions alignment and CPU's execution pipeline. Eg.: #include int main() { size_t n = 0; while (n++ asm( "nop;" "nop;" "nop;" ); ; std::cout
@TheBuilder
8 ай бұрын
good idea but not something people should be doing by hand
@NikPower-gs6hs
5 ай бұрын
@@TheBuilderif the compiler would not eliminate the loop completely then it would add nops with strong optimization and I can tell you that from experience
@NikPower-gs6hs
5 ай бұрын
arguably inline assembly might be a cheat in Cpps favor but yes it would be much better on newer processors not only because of the pipeline but also because of the instruction fetching from memory reading multiple bytes per clock cycle which lead to filling the pipeline itself
@1Naif Жыл бұрын
now do it with JavaScript
@TurtlemanLiam4 ай бұрын
also depends on what your running it on
@osu94006 ай бұрын
If you set a constant for 1,000,000,000 does that impact performance?
@laustinspeiss Жыл бұрын
Python is a relevant language for some tasks, but it’s main claim is it’s a modern interpreted language - easy to teach. A few years ago, it would have been BASIC, compiled BASIC, then Pascal. Java tried to slide in, but was pigeonholed for slow web applications. Things have to move forward, just like C, C++ and so on.
@user-td8mm1sy3j
7 ай бұрын
«««slow web applications»»»😁😁😁 Then what is not in your opinion?
@JohnBoen Жыл бұрын
Nobody just counts- except to understand the overhead. The things I would do at each increment are probably written in C, and likely designed to run on a GPU. I use python to execute functions in libraries. These are likely to be faster implementations of code than I could write in any language simply because they are typically open source and have lots of eyes on them. Was that the point- python is slow at loops?
@mixomax1161 Жыл бұрын
if you use a for loop, it ran (on my computer) in 44 secs. for x in range(1_000_000_000): n = 1 print(x)
@ECoventry Жыл бұрын
Did you include the time it took to write? Or compile?
@TheBuilder
Жыл бұрын
its in the video if you want to count it. i only sped up the execution of pythons code
@joytimmermans Жыл бұрын
Well you should always use the for with range in python if you can. Since that is C under the hood (in python 3). So kinda misleading. For more info look at m_coding’s video
@Ruchunteur
Жыл бұрын
It still slow though. I tried this: ``` n = 0; for _ in range(1_000_000_000): n+=1 print(n) ``` and it took 1m38s to finish
@joytimmermans
Жыл бұрын
@@Ruchunteur That is true, but it is faster then the while loop, you can even speed it up more with pure python to just use build in functions instead of using the for looping. max(range(1_000_000_000) speed is up from 1m30sec to 19sec. you can then speed this up more with numpy but also you can speed it up more with just math and seeing that the highest one will be 1_000_000_000 and then just print 1_000_000_000 making it run in 0.5 sec. would reccomend the mcoding video kzread.info/dash/bejne/g5uZ2NtwZcbVaMY.html for a explanation. but yea that is the dangers with python it can get really really slow if you dont know what you are doing
@r-tierney Жыл бұрын
I got 46 seconds using a while loop and 43 seconds using a for loop in python3.10.6.
@leosmi1
Жыл бұрын
Try 3.11
@alejandrosrwebmaster
Жыл бұрын
try C
@IncognitoDeveloper3 ай бұрын
have you tried constexpr in c++?
@CreachterZ3 ай бұрын
What’s up with the high commas?
@cmilkau Жыл бұрын
Idk whether it's still the case but Pypy (a python interpreter designed for speed) used to beat C++ on some regular expression benchmark (basically C++ had to redo all the work for every iteration whereas the JIT could hardwire the regular expression and optimize it).
@asuasuasu
Жыл бұрын
if the comparison was against std::regex, then that's no surprise, because std::regex is hilariously slow. like, "outperformed by literally any other option" slow. CTRE would be a different story, though :) tracing JITs are interesting tech though! there are definitely cases where it would be totally expected to trash an AOT compiler's optimizations.
@cmilkau
Жыл бұрын
@@asuasuasu JIT shine when you have data that is constant in practice but variable in theory. Like, matching repeatedly against a fixed regex. A precompiled regex lib has to analyse the regex every time. A JIT can compile a short program that represents the regex.
@donovan6320
Жыл бұрын
@@cmilkau but also std::regex is slow and you should never really use it.
@alanramirezherrera7485
6 ай бұрын
@@cmilkau C++'s std::regex is not a good choice (nor a good way to benchmark C++ vs anything else), it is slow due to it's design, almost anything outperforms it.
@maanavsingh1914
5 ай бұрын
@@cmilkau you can harness similar optimizations on compiled languages using PGO with a modern compiler to generate more optimized machine code for your input space.
@AndreasPinkert Жыл бұрын
The thing is that the C++ compiler will understand the loop and optimise on its own. -O3 does the trick. The loop will not even be generated as machine code. check compiler explorer.
@floxy709Ай бұрын
I'm new to this, but how much faster would an assembly language be than c++?
@TheBuilder
Ай бұрын
the C++ compiler generates assembly, so it's not much of a comparison, unless you're using specialized instructions which your compiler is not aware of
@citizenclownАй бұрын
Does Python count it in a default speed that unless specified, is slow? Or is it just that bad?
@TheBuilder
Ай бұрын
if you want to count in python using the standard interpreter in the standard way, yes it's that slow.
@benu5365 Жыл бұрын
I would point out that while loops are actually slower than for loops in python, but i guess its fair because you used while loop in c++ too.
@vadiks20032
Жыл бұрын
why are they slower wtf
@tipoima
Жыл бұрын
@@vadiks20032 Probably something gets optimized if the compiler knows how long the loop will run for. Then again, I also heard that all for loops in python are while loops under the hood
@monochromeart7311
Жыл бұрын
In python, while-loops are faster than for-loops. Python's while-loops are exactly like C while-loops, but Python for-loops are more complex and contain more overhead. Python's for-loop has to call "next()" on an object to fetch the next value, but "next()" tells you it doesn't have any more values using an exception which has to be caught and used to break out of the for-loop. It can be implemented using a while-loop and a try-except block.
@AnimatorArt24
Жыл бұрын
@@monochromeart7311 In python, while loops are slower. stackoverflow /questions/1377429/what-is-faster-in-python-while-or-for-xrange
@monochromeart7311
Жыл бұрын
@@AnimatorArt24 that's a stackoverflow question from 13 years ago, about Python 2's xrange. Python 3 doesn't have xrange anymore, and the language went through many changes in 13 years.
@lenoirx7 ай бұрын
You can do a for loop instead in Python to optimize it even further
@markpozsar5785
6 ай бұрын
Or don't ask python to do things it isn't meant to do
@ruadeil_zabelin4 ай бұрын
If you were to properly built that with optimizations it would be instant since the compiler will work out you're not actually doing anything and just handle it compile-time. Clang is very good at that. You can enforce it by using a constexpr function to do the counting.
@omicron296 Жыл бұрын
Olá! Qual IDE você usou para programar? Vlw pelo vídeo!
@heroe1486
Жыл бұрын
If you ask about this video that's vim, it's a text editor not IDE, although you can bring IDE functionalities via plugins
@TheBuilder
Жыл бұрын
Honestly I don't recommend Vim for writing code, just use Visual Studio and take it easy
@user-ef9nv2fy7g Жыл бұрын
In C++ u can use ++n as probably the fastest way to increase varlue by 1. Also for loop can be faster. Python for loop is runnig C for loop so it would be much faster.
@zephor6664
6 ай бұрын
Why would ++n be faster? It's still the same assembly instructions right? Isn't it just returning before the other instructions?
@decode9242
6 ай бұрын
@@zephor6664 It may be faster, since i++ usually cannot be implemented without an intermediate copy, but ++i is done in place and returns a reference to itself.
@vladimirarnost8020
6 ай бұрын
@@decode9242 Both ++i and i++ produce the same INC instruction for integers. There is no difference. If you take their value, e.g. x = ++i; vs x = i++, then there is a difference of _when_ the value if i is copied to x but i is still simply incremented if it resides in a register in most cases. Depending on the context, the compiler might also use a LEA instruction to perform the arithmetic if it deems it beneficial. Where the prefix vs. postfix notation _may_ make difference is with C++ iterators. It's generally preferable to use the prefix form, i.e. ++it. If the ++operator is inlined, even the postfix form might actually result in identical code if the value of it++ is not used anywhere, the temporary copy is optimised away. It depends on many factors, including the compiler type, version, CPU type, register size, surrounding code, etc.
Пікірлер: 3 200
You can highly optimize the Python code by setting n = 1 billion before the loop begins.
@Nohomosapien
Жыл бұрын
Yeah and also the c++ one. But maybe he did that for a reason
@user-gw4jp3xg3n
Жыл бұрын
@@Nohomosapien bro really dodged the joke.
@Nohomosapien
Жыл бұрын
@@user-gw4jp3xg3n Oh yeah, can you make me understand the "joke"?
@blubaylon
Жыл бұрын
@@Nohomosapien the joke was that the whole point was to speed test it, not to actually have "1000000000" in the console. So it makes no sense to write n = 1 billion lol
@petrurk6835
Жыл бұрын
@@Nohomosapien are you that dumb bro
You see, Python is actually good since it gives you time to get a glass of water, do something, play a game, graduate and get a diploma, get a job, witness the year 3000, all while the compiler is doing its thing.
@budgethvick225
Жыл бұрын
Isnt python interpreted?
@lloyd26
Жыл бұрын
@@budgethvick225 It is.
@nvcbl
Жыл бұрын
@@budgethvick225 it gets compiled then interpreted
@sks2227
Жыл бұрын
@@nvcbl tru
@narrator589
Жыл бұрын
Python is not a compiler genius
Fun fact: the -O2 flag on the gcc compiler will most likely optimize the C++ program to the point that the result is immediate…because it generates machine code that just puts the number 1,000,000,000 directly into the CPU register rather than actually counting anything. At least this is what happened when I tried it with plain C.
@bspringer
5 ай бұрын
Just make the variable volatile then
@kylecrane4376
4 ай бұрын
My first thought as well. The compiler will see that absolutely nothing is done with that value of (n) and simply remove the looping
@wumi2419
4 ай бұрын
Yeah, I was surprised when it did't happen.
@jingato
4 ай бұрын
set it from user input with cin
@marc_frank
4 ай бұрын
would that still happen if you printed every number to the console?
This is a great showcase of how much python has improved over the years, I mean this would probably not finish a few years ago.
@jasonscala5834
4 ай бұрын
😂😂😂😂😂😂😂😂
@ronald3836
4 ай бұрын
So a few years ago the fastest way to run this program was to first wait a few years.
@chadmwest
2 ай бұрын
Talk about looking on the bright side...
@cheatoffchannel6320
Ай бұрын
@@ronald3836 😂😂😂
I am really surprised that Python was only about 50 times slower.
@TheBuilder
Жыл бұрын
I didn't enable any optimizations in the compiler
@ujin981
Жыл бұрын
c=2.432; p=112.447; p/c >>> 46.23643092105264
@douglas5097
Жыл бұрын
lol
@user-tq9bu6ki2h
Жыл бұрын
@@TheBuilder the only avalible optimisation is just to skip iterations and add billion at once. Compiling with optimisation flag will change nothing or will make the test meaningless, I think.
@TheBuilder
Жыл бұрын
there are so many that the compiler does a better job optimizing the code. with python its not an option but any language can be equally fast
I told one of my professors that python was probably the best language to learn about parallelism and concurrency. He looked like I just admitted to support dog fighting. I then told him that python was so slow and inefficient, you would be able to visibly see the time difference from running on multiple threads. He laughed.
@croma2068
Жыл бұрын
Every time I stand up for Python people look at me like I just quoted Hitler
@ethannelson8656
Жыл бұрын
@@croma2068 It does have some niche uses. And I honestly believe it should be taught to children instead of cursive. That being said, it is pretty slow. And when its not slow, its because its using some other language.
@TheBuilder
Жыл бұрын
there are issues with the design of the language but the speed is fine for what i use it for
@noornasri5753
Жыл бұрын
Python is honestly the best. Sure if you're working on a large product or in a competitive setting, you'll need Cpp, Java, or sometimes C. But languages are just syntax, after a while using a new language is just deciding on the best language for the task then a few google searches. Python has so many uses, not just for learning. It's very heavy in ml, has many useful libraries (graphing, numpy), and can do straight up magic compared to other languages. Whenever I want to automate or check something, I just open idle. Edit: people replying about the "magic" just being simple pseudocode, yes that's exactly right lol. In just a few seconds I can reformat data with nested dict/list comprehensions into a structure that would take a dozen lines in other languages. I know lots of the stuff are written in C/Cpp anyways, that's like saying go use assembly because everything ends up being like that anyways. My whole point is that python is extremely useful, obviously there's a time and place.
@Metruzanca
Жыл бұрын
@@noornasri5753 "straight up magic" aka it can do what other languages do in slightly shorter syntax but it by no means has an advantage over other languages library wise. The only reasons python is so heavily used are: 1. its installed by default on all major linux distros, so its a prime choice for automation without further setup on fresh boxes. 2. Due to its simple syntax, its been picked up by data scientists to use for ML, but mind you ALL the heavy lifting is done in C++ so you could easily take say javascript which is also very easy to use (and has equivalent packages for everything) but is also much faster (using this shitty benchmark, written in node I get performance thats just a few ms slowler than c++) Python is not the best, never will be. Its just a very conveniently placed language. Want a language that actually does magic that no other language can? Learn rust.
Tip: You can use underscores in Python to separate numbers. Example: 1_000_000_000
@Injinct
5 ай бұрын
thanks
@Zorcky-2C
4 ай бұрын
Wtf is notation!? That is so ugly
@living-in-ohio
4 ай бұрын
Aint spaces just better
@RedHair651
3 ай бұрын
It won't work @@living-in-ohio
@ieatthighs
3 ай бұрын
@@living-in-ohioaren't*
The catch: it doesn't include compiler optimizations on C++ part. Otherwise it would probably turn into just "cout
I once tried counting to 1 Billion in my head. It took me a few centuries. I am glad I finally finished with that.
@TheBuilder
Жыл бұрын
same tbh
@Clayne151
4 ай бұрын
Me too, but I optimized the loop und just thought of 1 billion.
@MrMeaty6
Ай бұрын
bro how slow where u counting`??? 1 bil seconds is 31 years
@mik8352
Ай бұрын
@@MrMeaty6 Well, @filipburcevski9566 is right because it's going to take you more than one second to name each number... So yeah, it's going to take a few centuries.
@marjensendk
Ай бұрын
try saying 555.555.555 in one second :)
the semicolon in python is just perfect as someone who write in C++
@TheBuilder
Жыл бұрын
Muscle memory 💪
@listafe4938
Жыл бұрын
Also parentheses in the condition
@bobbyfeet2240
Жыл бұрын
I cut my teeth on C and only came to Python for work purposes target recently. I'm often told in coffee reviews that I'm getting "paren happy" in my conditionals and a few other places. Not so much an issue with semicolons, weirdly.
@usernamerequired788
Жыл бұрын
@@bobbyfeet2240 yeah. when I do python I’m like well why shouldn’t I use parentheses if it still works after I put them in
@AWriterWandering
Жыл бұрын
Funny thing is you can write semicolons in Python if you really want to. It basically just ignores them.
I had never delved into programming before, but this seemed so straightforward that I couldn't resist giving it a try. Using VS Code, I successfully executed it! Thank you; it was an enjoyable experience!
@TheBuilder
4 ай бұрын
Glad you enjoyed it
@mkapper9800
Ай бұрын
AI bot 😅
I'm actually planning to work on a Python-like compiled programming language soon. This video remotivated me. Thank you
@TheBuilder
Жыл бұрын
Golang or building your own?
@tigrankhachatryan6119
Жыл бұрын
@@TheBuilder My own, though I'm going to use LLVM as a backend because I don't want to lose my sanity. It's gonna support both high-level and low-level features. Also, it's gonna be gradually typed. I can tell you more about it if you want
@TheBuilder
Жыл бұрын
It's not something I'm familiar with. but if you want to share more you can contact me through email or join the discord
@RedHair651
3 ай бұрын
Nim?
@tigrankhachatryan6119
3 ай бұрын
@@RedHair651 Nim's not that Pythonic even though it's somewhat more humane than the average language
Hey give Python a break! I bet you can't count to a billion that quickly!
@TheBuilder
Жыл бұрын
python does in 2minutes what it would take the average person a life time to do
@dekippiesip
Жыл бұрын
@@TheBuilder about 30 years if 1 second stands for 1 number.
@technolus5742
Жыл бұрын
@@dekippiesip and don't forget numbers get harder and longer to count as you go
@ProgThoughts
Жыл бұрын
@@technolus5742 Something else gets harder and longer
@GamingFrazix
Жыл бұрын
@@ProgThoughts yea- but he probably dosent have that so leave him alone lmao
I studied C++ and C# in university, but before that I was learning python (through online courses) for exam. Now it is funny to remember how teacher said that if we won’t optimise our code, it will calculate for longer than the exam lasts
@herseem
Жыл бұрын
When I was at university (ok, it was Thames Poly. It only became a university when I left), if you wanted to add a gigabyte of memory to your computer you'd first have to apply for planning permission to build an extension. Now, 32GB comes in those handly blister packs sometimes near the till for 'impulse purchases'.
@rickintexas1584
Жыл бұрын
@@herseem I know the feeling. I wrote my first programs in 1978 in high school. I wrote my first professional programs in Fortran in 1984 on a VAX computer shared by about 20 people. It only had about 256 MB of RAM to support all the users.
@AlexRodriguez-gb9ez
Жыл бұрын
@Game Plays 1230 Avoid dynamic features in inner loops, cache, use aggregate functions like the array functions in numpy since they are written in C and use vector instructions
@ilsignoredellaluce2234
7 ай бұрын
This is so true. I had to rewrite an entire program during an exam because the way i wrote It the first time was so slow that i couldn't reiterate it the number of times needed before running out of time
@user-rb9qm5wr2l
6 ай бұрын
Just had to make the thumbsup an even 1000.
You can get even faster c++ code if you enable optimizations with the -O2 flag. Although it's possible that the compiler optimizes the loop and removes it 😅
@TheBuilder
Жыл бұрын
that would be unfair since Python still dutifully does all those additions
@jormaig
Жыл бұрын
@@TheBuilder True although this also highlights the power of compiled languages that can optimise away unnecessary computation
@rb1471
Жыл бұрын
@@jormaig In python we call it optimizing away the software engineer
@alexanderd.7818
Жыл бұрын
There are ways to ensure that loop is not removed. #include #include #include uint32_t n; int main() { clock_t begin = clock(); volatile int deopt; for (n = 0; n != 1000000000; ++n) { (void) deopt; } clock_t end = clock(); double spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("%f ", spent); } 0.350250 with -O3, 0.98 with -O0.
@alexanderd.7818
Жыл бұрын
@@MTQvODg Hmmm… And how exactly would you suggest to benchmark it in a “good” way?
You can use an underscore as separator for intergers in python for better readability btw
@leaks1965
9 ай бұрын
but who needs readability in a 2 line file???
You might think that the major time difference was because he used different coding languages, but python would’ve been way faster if he just removed a few zeros.
@Superdeeep
Жыл бұрын
eaxtly and it would have been even more long for c++ if u added more zeroes
@weetabixharry
Жыл бұрын
These are the facts that they don't want you to know.
@jpsytaccount
Жыл бұрын
My question is, why not just set N = 999,999,999? Wouldn’t that speed things up?
@Superdeeep
Жыл бұрын
@@jpsytaccount what if and this is really genius. He puts it to 999,999,998
@ohneko6193
Жыл бұрын
How about we just remove the “1” and it’ll be infinitely faster
Sometimes you don’t need the program to run quickly. You just need it to run. That’s why I love Python. Although it’s certainly not the fastest language, its ease of use is great for beginners, and I can write a program quicker in Python than I can in c++. I don’t think I would be a programmer if Python didn’t exist, quite honestly. And keep in mind I love C++ too just for different reasons.
@user-wx1ns5hf3h
Жыл бұрын
You said everything right. However, there are people who are sure that there is only 1 language for all tasks in the world and that is python. I say this because I know a "hacker" who brutforce passwords in python (brutforce to find hash colision) and wondered why it took so long
@bljet4388
Жыл бұрын
Bruh tell us another thing everybody already knows
@ruynobrega6918
Жыл бұрын
@@user-wx1ns5hf3h you can use python for everything, as long as the libs are compiled in C lmao
@ruynobrega6918
Жыл бұрын
Jokes aside, the level of draft code you can make in python is unmatched by any other language. And honestly, for most stuff nowadays python is trully enough.
@factChecker01
Жыл бұрын
@@ruynobrega6918 That depends on the application. There are a lot of languages that are MUCH easier to use in particular applications. I have done a lot of scripting programs in Perl and it is much easier than Python for that. And MATLAB is much easier for many engineering applications.
We're studying FEM/FEA by implementing it in Python code atm. And while it sits there forever using 26GB RAM and 96% CPU I think to myself, how fast would it be if written in C++? (Maybe it wouldn't be that bad of a difference since Numpy is written in C though. Idk really...) However, I wouldn't stand a chance to be able to implement the ideas/concepts we are using it for in such a short time if it was written in C++... It would at least double if not triple the time spent on the project is my guess 😅 Off course such an application would be implemented in C++ for an actual program. But each tool has its place. For us it is having an easy language, in order to learn FEA by implementing it in code, the coding part being secondary to the concepts we're coding at least within the course we're taking. That's where python shines I guess. It minimizes "barrier" between the scientific/engineering concept and the code implentation, and it's a great language for just that reason. Different tools for different purposes.
@MajinSaha
Жыл бұрын
If "the coding part is secondary to concepts", then MATLAB/Octave beat Python in that regard. Yet it's Python that gets all the f*ing praise smh.
@mujtabaalam5907
7 ай бұрын
@@MajinSahaMathematica is better
@piotrc966
4 ай бұрын
"the coding part being secondary to the concepts" always code is the second. It doesn't matter what you're doing whether it's a store or business rules in DDD or a game. In our company, we model the business in DDD using C#. (python is too slow and has poor objectivity - only by convention).
@Salzui
Ай бұрын
Did you consider using PyPy if applicable?
@eeshandev5081
26 күн бұрын
C++ and Fortran are best if you're solving CFD or FEA problems because as far as I know, C++ and Fortran are fastest when handling multidimensional array. OpenFOAM has its entire library written in C++ and is a great open source CFD solver.
Thank you for this video!
@TheBuilder
Жыл бұрын
You bet!
Please turn on -O2/-O3 in c++ the time will be mesured in miliseconds (There will be no loop...)
@morgard211
Жыл бұрын
Is there a reason why that's not done on default? How would the assembly code look like? Would it just be an add instruction bilion times? Wouldn't that binary be absurdly large?
@TheBuilder
Жыл бұрын
@@morgard211 sometimes optimization gets in the way of debugging so its an option. Enabling optimizations would probably result in the compiler computing the loop at compile time and giving you a binary that just prints the value
@chri-k
Жыл бұрын
@@morgard211 also optimization is not perfect and sometimes breaks functionality in complex programs, requiring additional time to figure out what the optimized did and how to tell it to not do that.
@mmyd2405
Жыл бұрын
@@morgard211 Assembly is also capable of loops bro (jumps/calls) So about 5 lines are enough for this (if you actually loop through it unoptimized) If you Compile on -O3 the compiler would register the loops and set the variable to 1000000 instantly instead of adding 1000000 times
@botondhorvath1445
Жыл бұрын
@@chri-k Optimalization only breaks code if there is UB in it. (Assumeing that you have a good compiler) If it breaks a complex program then that is because someone wrote a wrong code somewhere in it. But if the faulty code is in a wrong place, then it is extreamly hard to figure out how to fix it, maybe harder than it worth.
Python enjoyers: NOOOOOO you're not doing it right. Rust enjoyers: Let me try my best to show why Rust is faster than C++ than this video does, and why it should be the best! C++ Enjoyers: I wonder which libraries written in C++ they're going to use...
@Longus07
Жыл бұрын
As far as I know most of the libraries used by python or rust are written in c not c++ Edit: just to clarify rust mostly uses libraries written in rust but there still are a lot of c libraries which are used in rust mostly because they are already high performance, well established and we'll documented.
@shengalabu8050
Жыл бұрын
@@Longus07 isn't c also c++ cuz if you run c code in c++ it'll still work so technically all c code is c++ but weaker
@Longus07
Жыл бұрын
@@shengalabu8050 NO
@Longus07
Жыл бұрын
@@shengalabu8050 most of Java code will run in c# excluding the libraries and imports
@shengalabu8050
Жыл бұрын
@@Longus07bruh why you talking bout java?
It would be really nice to include javascript timings. On my machine: C++ is 0.66s, Python is 42.37, and JS (Node) is (amazingly) 0.53s. Presumably V8 is doing some crazy optimization, so I added a Math.random() check in the loop, and it went up to 6.3 seconds. Still very impressive.
@nvcbl
Жыл бұрын
nodejs is now the god of all languages
@youtubedeletedmyaccountlma2263
Жыл бұрын
@@nvcbl nah is not. I hate nodejs
@fabricebalan
Жыл бұрын
there is something wrong with your c++ compiler or computer then
@TheForge47
Жыл бұрын
@@nvcbl lul this pice of shut up mark and Go away
@diegocantelli
Жыл бұрын
Ricky, i don’t know…
Can we get a demonstration of how long it takes to write and debug some c++ data processing tasks that python can do in one line of code?
Isn't For Loop like twice as fast compared to While Loop in Python? C++ would still obviously win but I believe Python's score would look better.
@TheBuilder
Жыл бұрын
Using the Numba library can make Python comparable to other languages for simple operations.
@unknown3158
Жыл бұрын
@@TheBuilder Yes, with JIT. Doesn’t work for everything though.
@royler8848
Жыл бұрын
@@TheBuilder it's not even that, the range psudo iterator is implemented in c, not in python. You spend much more time running c code when using range compared to a manual while loop
@Eknoma
Жыл бұрын
Pythons for loop is like 5 times slower than while, as it basically uses a while loop, but also try/except, which majorly slows it down
@moneymouse
Жыл бұрын
@@Eknoma kzread.info/dash/bejne/g5uZ2NtwZcbVaMY.html No it is not
To be honest, Python was my first language to then go on to Java, C and C++. Its very good to learn with very high level and general programming but when you dig deeper, it falls short except from certain tasks like machine learning.
@TheBuilder
Жыл бұрын
Similar story with me, except I started with C, switched to Python and thought it was the best thing ever since I could write 5 lines of code to do practical things....then I started working and realized lacking a strict type system makes Python and JavaScript prone to errors especially on larger projects
@sepxviii731
Жыл бұрын
Machine learning in python is done in C...
@dtikvxcdgjbv7975
Жыл бұрын
@@sepxviii731 good one 😂👍
@sepxviii731
Жыл бұрын
@Tarik B. try Julia
@sepxviii731
Жыл бұрын
@Tarik B. You live in the past century. Julia sometimes is even faster than C
If optimisations were enabled (even -O1), any decent C++ compiler (such as Clang++) would replace your entire program with `std::cout
If you use -O2 or higher, the C++ loop gets folded completely, making it even faster
@ChrisM541
6 ай бұрын
You mean unrolled?
@vladimirarnost8020
6 ай бұрын
@@ChrisM541No, he means replaced with a precomputed constant, i.e. 1000000000.
@ChrisM541
6 ай бұрын
@@vladimirarnost8020 Thanks, that's interesting. Is there ever a danger this type of 'optimisation' happens in the wrong situation?...where it is absolutely not wanted?
@vladimirarnost8020
6 ай бұрын
@@ChrisM541 Good question. The compiler is usually doing a good job not breaking code by over-optimising it. However, when the goal of such a loop is to wait for a certain amount of time, e.g. in embedded code touching hardware directly, the loop removal might break such code as it would simply run too fast.
@NikPower-gs6hs
5 ай бұрын
@@vladimirarnost8020you can specify if functions or certain code parts get optimized or not just for that purpose
But there is a package for that import counting_library, speed speed(counting_library.count(100000000))
@xCwieCHRISx
2 ай бұрын
and good packages are written in C 😁, like numpy. Python is just a powerful API for C libraries.
Now process data on each iteration and you'll see how python performance decreases dramatically. Depending of the case I've noticed that python is a about 500× slower. For example try calling a method within a custom class.
@christianm4906
Жыл бұрын
@@ILubBLOfficial that's OK. However not everything can be run with those libraries. I'd prefer integrating python with C++ using a wrapper such as Pybind11, SIP, shivoken, boost::python, etc . That approach for optimisation is much more powerful as it brings the best of python and C/C++ together. By the way, Numpy is a descent approach. However Eigen which is the C++ counterpart is much faster and optimised. Pandas is a huge package. Too many things there that aren't always necessary.
@christianm4906
Жыл бұрын
@@themystic5935 realistically speaking. Many companies specially in embedded systems, prototype in python and rewrite everything in C/C++ for production. I still consider that Python and C++ work fine together. They are just tools not religion.
@christianm4906
Жыл бұрын
@@ILubBLOfficial Eigen which is the C++ equivalent to numpy is about 20 or 30 times faster than numpy. And also, not always you can avoid Python bottlenecks. However I don't critice Python for that. I think it is still a great scripting tool for a range of applications. What I critice is that there seems to emerge a new generation of developers, most of them beginners that frenetically love a specific programming language as if it were a sort of religion. They wrongly think they can do everything in a single programming language and they don't admit the weaknesses of their favourite tool. They are just tools, not religious. There are also many areas in which Python is a better choice than other tools, but when it comes to optimisation, performance, and concurrency, Python performs very poorly. Probably worst than the vast majority of its competitors, and that's why it is recommended to learn more than just python.
@AlexRodriguez-gb9ez
Жыл бұрын
@@christianm4906 Where did you get your statistics from. From what I see its more like 2-15x slower.
Don't you think c plus plus compiler removed effectively empty cycle from assembly code?
I had my “road to Damascus” moment in 1981 when I wrote and ran a similar routine on the Original IBM PC. . . first, interpreted BASIC, then Compiled BASIC, then in C. I was showing my kids. Well, I was blown away. Even though I had written some “pretty good” code (worth about $1,000,000) for my employer, I NEVERwrote another line in BASIC.
@wrmusic8736
5 ай бұрын
My first programming experience was with ZX Basic. Speccy allowed to do Assembly (or rather literal machine code) by "poking" memory (e.g. storing literal values in it and then calling a desired memory address to execute), but sadly my child brain couldn't comprehend it. Basic was slow of course and I had to scratch my head trying to understand how all the other programs ran so fast for a while. At some point I learned there was a C editor, but I couldn't find the tape anywhere.
For loop in python is faster than while, should use first one
@TheBuilder
Жыл бұрын
It's faster but not by much
@rivercape982
Ай бұрын
@@TheBuilderit is much faster, around double
@Jp-ue8xz
Ай бұрын
@@TheBuilder uhh... "from numba import jit". Wrap counter in function with decorator @jit(looplift=True). Same operation takes just well under 1s
0:28 I KNEW IT 😂
@TheBuilder
Жыл бұрын
Python is actually faster if you ignore the numbers
A simple but effective example for sure!
so glad i started learning c++ again after doing javascript and now also learning rust
You can get the time down to 25.8 seconds using a for loop instead of a while loop in python.
@swiftz6098
Жыл бұрын
I lied, that was without printing the number. for loops are still faster though.
@furkanunsal5814
Жыл бұрын
@@swiftz6098 well, that is absurd.
@wrnlb666
Жыл бұрын
he can also make the C++ Program about 4 times faster using register int n
@arthur1112132
Жыл бұрын
@@wrnlb666 the compiler should automatically do that tho
@wrnlb666
Жыл бұрын
@@arthur1112132 But it's c/c++, so the compiler gives you the power to choose if you, the creater of your own code, want to let the compiler do that or not.
You really added a semicolon in Python 😂
@SamMcPieVTOL
Жыл бұрын
Python enjoyers be like: oh my gosh you added STRUCTURE and READABILITY to your code?? lol lmao wtf is that what are you?? A loser????
@Morimove
Жыл бұрын
this is called muscle memory 😂
@TheBuilder
Жыл бұрын
subconscious bias
why did you used size_t instead of int? sorry for that nooby question, it seems curious for me :p
I ran it in Common Lisp and Racket (translated by ChatGPT because I still suck at them) on Linux Mint with a 5600x CPU: - Python took 39 seconds. - CLisp using SBCL took 0.222 seconds. - I gave up on GNU Clisp after 6 minutes. - Racket took 0.845 seconds. I altered them to print the results to make sure they actually did the task, and they printed one billion. The Racket script is relatively complicated and might not be optimized well. But these results are crazy!
I think there’s some settings you can tweak for cout speeds. I saw it at an article wrote by geeks for geeks or something it’s about competitive coding
@hi-tk4hu
Жыл бұрын
Yes n +=1 is faster than n =n+1 for some reason
@mactalk2871
Жыл бұрын
@@mb_entity cout is called every time there is a iirc, maybe im mising it up with printf
@04ZFZ
Жыл бұрын
Iirc it's cin.tie(0); sync_with_stdio(false);
@unknown3158
Жыл бұрын
@@mb_entity You are not dumb, you are actually correct.
@alwayslg
Жыл бұрын
@@04ZFZ I think this is it
I've just tried this with pypy: c++ 1.04s python 40.21s pypy 1.01s
@xEndless11
3 ай бұрын
wow nice! I didn't even know there was something even faster, i will figured out ^^
@thecheesybagel8589
2 ай бұрын
this is because the back-end of python in written in C. you can get the python interpreter to loop in C rather than in python
@felixmarshall8614
Ай бұрын
@@thecheesybagel8589 exactly. It was strange for me to watch speed competitions when the developer did not use all the capabilities of Python for this
@PatrykGlogowski
Ай бұрын
@@felixmarshall8614 he also dont use capabilities of c++ -o2
I didn't see printed char on console. How we can check this two examples are equivalent?
A modern compiler such as the GNU C++ compiler you use in the video, do many passes and optimisations. There is a possibility the compiler may have changed the code to something other than 1 billion increment instructions that would make this comparison fair. However the point still stands that python will always be much slower for operations like this; it's not the right tool for this job, just as you wouldn't use a screwdriver to punch a nail into a wall, though the screwdriver has uses of it's own
@TheBuilder
6 ай бұрын
Optimizations were turned off in the compiler, counting up to a billion actually takes a second or two on most processors
2.5s is excessively high, whats your CPU? I get ~250 ms on C# JIT optimized, ~750 ms on unoptimized with Ryzen 7 Laptop CPU
@eherlitz
4 ай бұрын
Got 290 ms on c# compiled for release and run on a linux laptop with a Xeon E-2286M CPU.
@Jp-ue8xz
Ай бұрын
IF I run this raw C with no optimization flags in my asus potatobook from 2016, then I get similar times as this guy. But just using -O2 flag drops it to less than 10ms. It's an incredibly weird "flex" anyway considering python also takes well under a second to do this if you wrap the thing in a function and use a JIT compiler
Okay seriously how can you live with a tab width of EIGHT? And also why do you have different tab sizes for C++ and Python?
@SkySentry7
3 ай бұрын
mine is 2😂
@Valentyn007
Ай бұрын
Mine is -1 😁
@SkySentry7
Ай бұрын
@@Valentyn007 🗿
@KanashimiMusic
Ай бұрын
@@SkySentry7 While I personally don't like 2, I think it's tolerable at the very least lmao
@KanashimiMusic
Ай бұрын
@@Valentyn007 giga based
Perfect example, why there are optimized languages for different usecases. This comparison is like compare a kitchen knife and a leatherman by chopping onions with both.... or by turning a screw into wood with both.
What this example misses is the fact that most "python" libraries actually are built on top of C++ and/or Rust for the heavy lifting. If you are writing Python that doesn't delegate processing to another library, you're doing it wrong. You can't conflate Python as a language choice with examples like these that no one would/should actually implement.
Dude it takes 341 milliseconds for nodejs on my machine. On what pre-world war machine are you running your C++ code for it to be so slow?
@TheBuilder
4 ай бұрын
Turn off optimizations
Can someone explain this to a non-programmer? Wouldn’t the code to the CPU’s be the same? Don’t compilers, even if they’re being done in real time, change the code into assembly instructions for the processor? I would assume that such a simple program would result in the same instructions being seen by the CPU.
@tholod
Ай бұрын
I know I am two months late to answer, but I think your question is interesting. Your mistake is to considered Python as a « compiled at runtime » language, which is not true. Compiled language are transformed to CPU instructions during compilation as you seem to know. Python is an interprated language, that means for each code line, the python program (python.exe or /bin/python) reads the line (reading a string is a set of CPU instructions), and updates its state in memory according to the python code. It is like there is a layer between CPU and code, the python code will never be translated into instructions. The python program is for python what the CPU is for C/C++ language : the executor. However the python program is made of CPU instructions,and running it to execute the code line takes CPU time to execute. The same applies to CPU, you can have an algorithm done with instructions that runs on a CPU, but you can also design a chip that is specified to do this same algorithm and it will be quite faster than the CPU (if it is well-designed) because there is one layer less (there is no more instructions that translates the algorithm). However you lose the versatility of a CPU which can execute different algorithms. It is the same with python, it is a language where programs can be run and debugged fastly because there is no compilation time, but with less efficiency than compiled language (some tools try to avoid that by compiling python code at runtime like Numba and get better performances).
So how do they compare with for loops instead of while loops?
Does that mean python is very slow as compared to c in running big blocks of code ?
@TheBuilder
Жыл бұрын
I think Python is faster than C when I want to get something practical done
@captainswing4040
Жыл бұрын
@@TheBuilder python is a great scripting language with enrmous support but it has a purpose and that is not same as that of C
@jebbi2570
Жыл бұрын
@@TheBuilder But it quickly become slow when the project evolves.
@taihuynhuc3135
Жыл бұрын
@@jebbi2570 How much your project will evolve anyway? Actually many softwares out there dont need to evolve that much.
@corex6109
Жыл бұрын
@@jebbi2570 The great thing about Python is that whenever you truly want/need C's speed, you can just write a shared library providing that functionality in C, then call it from Python. Of course this too has its limits, but it's a nice workaround for when there's one significant bottleneck.
for best optimization you can set n to 1 billion and use a prefix decrement inside the condition
@codingjq
7 ай бұрын
I thought gcc turns i++ into ++i automatically?
I want to see the compiled code to see if the compiler is able to optimize the loop out.
Python code’s 1st execution is also its compiling stage. On the 2nd run, it is way faster. You should have either calculated c++ compiling time + run time or compare python’s 2nd run
@sinoichi
4 ай бұрын
Python does not compile anything... it's interpreted language. Second faster run it's just cache layer, but it's only temporary :)
@catfan5618
4 ай бұрын
@@sinoichiWrong, it compiles the code into byte code which then gets interpreted.
@sinoichi
4 ай бұрын
@@catfan5618 Then you wouldn't need python installed. 😉 Sorry, python scripts are executed line by line by python interpreter.
@sinoichi
4 ай бұрын
@@catfan5618 And if you think it is compiled. So where does the binarie goes? Where is executable file? Because when you run python script it does not change it's form. It's still editable. Even if it would be compiled to RAM, there is no sense to not get compiled files.
@TheThilor
4 ай бұрын
@@sinoichi Compiled does not mean we get a binary. See Java, we compile our Code, but dont get a binary. Python compiles it code into bytecode and stores this into .pyc files.
I actually came across this recently. I was trying out micro-python for the first time on an RP2040 Rasberry Pi PIco W. The embedded version of "Hello world" is "Blinky", you blink the LED on and off. Wow! I figured out the gpio library, but I couldn't bother to find the "Delay" function/method/module, so just counted to 100,000. I was expecting to have to ramp that up much higher and thankful I didn't need to think about datatype in python.... but no. The LED blinked with about 1Hz frequency. counting to 100,000 took 500ms! To be honest I haven't switched it back on again. I don't think it's the RP2040's fault, I think it's python's fault. If I did that in C on the same board the LED would just look a little dim and flickery. If I did it in ASM it would just look like it was on.
@asuasuasu
Жыл бұрын
"counting up to a number" is a very bad baseline for comparisons. For one, these languages have extremely different performance characteristics. (Micro)Python is naively interpreted. It absolutely doesn't have advanced optimization passes that would make it able to reason about this. A C++ compiler will be able to make sense of your counting, and is likely to trash away your loop, 1. because it'd be able to figure out that you're just counting up to 100000, and 2. because you're probably not even using the value... so it can just optimize it away entirely. Though, if you need anything reasonably fast then MicroPython is not a good idea, for sure. I heavily use Python and I dislike the idea of using Python in embedded programming. Assembly is not a magic bullet. If you know your C/C++ and optimization, then dropping down to assembly is rather unlikely to let you write faster code.
@jackroutledge352
Жыл бұрын
Bear in mind that the raspberry pi foundation's goal is to teach people programming. Python is their standard language for everything they do (hence raspberry "pi"), because it's easy to learn. Having said that, you can program the pico in cpp as well.
@qwertykeyboard5901
7 ай бұрын
Ported an NQUEENS algorithm to both J2ME (SPH-M330) and an arduino (ATMEGA328P). The arduino was ~20% faster. Arduino UNO clones usually clock the ATMEGA328P at 16Mhz. The Samsung has a full 32bit ARM processor at (probably) 192Mhz. It might even utilize the "jazelle" instruction set. Thats honestly really fucking pathetic for Java. Needless to say, I was incredibly pleased to find out that my stupid conway GOL demo ported to C (Qualcomm BREW) was so fast that blinkers are a blur on screen.
I was curious to get the times on my machine. C : 1s740 Python: 47s Perl: 34s
@MrKrzysiek9991
Жыл бұрын
JS ~2.0 sec
@rodrigozayit
Жыл бұрын
java 0.025s
@ricardoangelesgomez8667
4 ай бұрын
Python on PyPy: 1.083s
Was this comparing just the initial compile times or the finished program? How did the c++ do 2.4 seconds? I ran the same thing in visual studio 15 minutes ago and it's still counting. You must have a beast of a workstation or I messed up somewhere.
@TheBuilder
Жыл бұрын
are you printing every single number?
@nathanwhite704
Жыл бұрын
@@TheBuilder yes.
@TheBuilder
Жыл бұрын
@@nathanwhite704 there's your problem
That's very odd. I just ran it now, and Python was faster than C(though not CPP), but it was both just above 1 second.
time to do this in other languages like lua, javascript and csharp
How do you show the time required like Real, User, System etc? Seems So cool 😀
@glidersuzuki5572
Жыл бұрын
That's the 'time' application he uses at beginning. Usage is as follows: time
@gazzalifahim
Жыл бұрын
@@glidersuzuki5572 Thanks a lot. 💯
@TheBuilder
Жыл бұрын
this
@bobuccman1424
Жыл бұрын
windows user when encountering built in unix commands be like
Would like to see an int wrapped in an object for another comparison.
while loops in python are terrible for performance if you are iterating many times. In reality you mainly use python for data and simple codes where you import libraries written in c and c++ which make it perform just as quick as low level languages. If you want to build anything big that isn't easily avaliable via a library you use a low level language, for simple quick things like data analysis python is pretty nice to use.
@TheBuilder
Жыл бұрын
yes
@aaronsteers
5 ай бұрын
Exactly. The reason Python ISN'T slow is because good python code handles control-of-flow in Python and heavy processing in another service. What you lose in raw power in higher-level language, you can gain back 10x in better design and maintainability overall, if you're doing it right. You can't imagine how many times I've seen code that can't be optimized because it's too convoluted and not enough people are actually able to contribute the obvious fixes that are needed.
Nice comparrison. However I think a lot of people are a bit too invested in efficient code. In many environments, computation time is much less expensive than coding time. So if you only have to solve a given task once or a few times, the computation cost is easily mitigated by the saving in coding time.
@sitting_nut
Жыл бұрын
Why do you think python coding time less than c++ coding time? maybe true about c if one codes from scratch (instead of including libraries) for say data structures etc. but definitely not true about c++.
@Hooverdreng
Жыл бұрын
@@sitting_nut I can’t speak for all disciplines. I am doing data analysis and measurement and control for experimental physics. And for that purpose Python is the faster and more flexible option. Could I write the same thing in C++ and have it be faster? Sure. But I don’t need to and using python my code will also be more accessible to people following up on my work. I don’t need an F1 car that only the cool kids know how to drive. I need a Ford that benefits more people.
@sitting_nut
Жыл бұрын
@@Hooverdreng iow you are supporting your bias with personal anecdotes instead of objective data (and say all that unironically while you are saying your work is about data analysis, measurement, and experimental physics). anyway, once again my point was that your claim in op, that there is a coding time increase for using c++ over python, is false. that point had nothing to do with f1 cars used as metaphors.
@cagefury3789
Жыл бұрын
@@sitting_nut Seriously? Idk, maybe he got that impression with a simple hello world? lol. In c++ you have to import/include a std library, use a bitshift operator and put it in a main function. In python you type "print".
@sitting_nut
Жыл бұрын
@@cagefury3789 if you know anything, you know you don't actually need to include std lib or io. and why do you need a bitshift operator in hello world? fact that you had to make up such absurdities to make your claim, indicate even you , ignorant as you obviously are , know that, claim there is a coding time increase for using c++ over python, is false. typically you pretend you don't know python scripting mostly consist in importing other libraries. and how is " "__name__ == “__main__”" , and other such nonsense to structure any significant program , an improvement on main function in c++?
By the way, these types of loops would normally just be optimized to print out 1 billion from the start.
@Hephasto
Жыл бұрын
I’d love to see C and assembly for comparison. But not shitty count, something more realistic
@petrjara7559
Жыл бұрын
@@Hephasto Nowadays if you use some better C compiler it generates like 95% perfect asm code. For "more realistic" = more complicated programs it's even faster to write in C unless you REALLY know how to optimize in assembly just because there is already 50 years of optimization experiences in the compiler
@donovan6320
Жыл бұрын
But that would have taken less than a millisecond.
@puppergump4117
Жыл бұрын
@@donovan6320 You can try it, just do the same loop but compile with the /02 or /03 flag. It won't compute values that aren't read. Now a better way to test how quickly a computer can increment would be to start a timer and use some time limit as the condition to exit the loop. The result should be in the hundreds of millions per second, but I'll test it myself in a sec
@donovan6320
Жыл бұрын
@@puppergump4117 I can too lol, would do it
What shell are you using here?
I got the same result in C and Python using huge random complex tasking with optimized code in Cython / CPython and better results with Pytorch. Python provides me interpreted and compiled worlds with simple code and few hours of programming.
That's a important trade off. Does anyone here have experimented compiling Python code with Cython or Numba? I wonder how it will perform in this situation. Also, now with Python 3.11 it got a bit faster. But still much slower than Cpp off course.
@spartanbirdz
Жыл бұрын
3.11 version made it 15% slower for me lol.
@agalliazzo
Жыл бұрын
Just tested in a RPi4: - Python 3.9 + Numba 2.257s - C++: 6.052 I, honestly, was not expecting this...
@marcotroster8247
Жыл бұрын
Numba needs to JIT compile your loop. It converts the code into C and compiles it on-the-fly. That's why the first execution is slow. If you use the function a lot, it's as fast as C. And it's even smart enough to put your vectorizable code onto the GPU without you noticing, it's crazy good 😂
@agalliazzo
Жыл бұрын
@@marcotroster8247 Really I was not expecting that with numba the time is about 1/3 of a plain c++ loop... I was expecting something similiar in performance, so 6s about...
@marcotroster8247
Жыл бұрын
@@agalliazzo Numba is really good at vectorizing loops 😂 I suppose it's doing multiple additions at once with SIMD optimizations or GPU 😎
You can make the C++ run even faster by using printf() instead of std::cout. I managed to reduce the speed to 50ms with just that change
@target844
Жыл бұрын
That is not the difference. You change is because of what optimization the compiler did. I god 30 microsecond for the code above and -O3 optimization. The compiler realise the final value of n do not depend on anything unknown at the time of compilation and can just set it to the final value and remove the while part completely. Test to add volatile as a keyword to n or test both print methods in the same compiler
@nolanfaught6974
Жыл бұрын
@@target844 Good catch, execution time was significantly slower once I used volatile. I've had bad experiences with std::cout in the past, to the point where almost 1/3 of my execution time was spent on basic I/O. A rewrote the backend to use `printf` and performance increased quite a bit.
Whe do you use postincrement? Isn't it more effective to use preincrement?
@viper_0097
3 ай бұрын
compiler can optimize that if using postincrement have not difference with preincrement
I’m new to programming. I’ve been learning intro python. Can someone explain why the languages have such different processing speed?
@TheBuilder
5 ай бұрын
every data type in Python is a lot more complicated compared to C or C++, for example, every time you interact with a number in Python, the program will call various other functions while in C or C++ the operation is only a few assembly instructions
C++ has the advantage of using register variables. That reduces variable memory accesses to zero while in the loop. Python must push and pop n on and off the stack.
@blip666
Жыл бұрын
How do you know this ?
@purdysanchez
Жыл бұрын
I too would like to see more info, but it's a pretty plausible explanation.
@ctleans6326
Жыл бұрын
@@blip666 Compiler explorer can show the assembly output of compiled programs and you can see it directly interacting with cpu registers (eax, edx, etc.). Cpu registers are far faster than memory accesses. I don't use python so I don't know how it works internally but it's physically impossible for a language to optimize with cpu registers without compiling to binary. There are way more reasons why c/cpp/rs are magnitudes faster than python. 1, yes, it is a compiled language so any "actions" are just one instruction to the cpu. 2 Static typing also makes it faster because memory is constant size and no need for extra memory to store types. 3. Static typing and other restrictions allow optimizing compilers, esp. llvm to analyze data flow and other stuff to inline/remove/optimize assembly. 4. garbage collectors do add overhead to the code, i don't think by much but languages without gc, especially rust, know exactly what parts of memory to deallocate.
@Fl4shback
Жыл бұрын
I would expect the compiler to just optimize the loop away and set the value to 1 billion...
@DemonixTB
Жыл бұрын
@@Fl4shback it would do that if any optimizations were enabled for the compilation in the video, the author said in another comment that it felt unfair to do since python cant do that, lol
True story, my friend and I went to a coding interview where they treated all languages the same and had a run-time limit. We both got the question, I used python w/ DP, he used C w/ brute force :)
@firstlast9813
10 ай бұрын
Dang! Brute force? 😂
@8BitGamerYT1
8 ай бұрын
And who did better
@howabout2138
18 күн бұрын
@@8BitGamerYT1the Python probably still runs and c brute force finished before guy fully lifted finger off enter
use for loop instead in python. for loops is basically written in c in cpython implementation, must to be faster than while statement
I thing gcc has some optimisations enabled by default. Is this also the same result without optimisations? It could just be that the compiler sees what the code is doing and simply sets n to a billion right off the bat
@ItsCOMMANDer_
4 ай бұрын
Only with "-On" flag where "n" is the optimisation level, with n >= 2 the for loop will be removed, below thta, nothing willl change
The cool thing about python is that there are so many ways to optimize things. Basic code like this may be really slow, but there are ways to 100x things like this
@uniquetobin4real
7 ай бұрын
Thats why i hate python... Never straight there are a billion ways to do the same thing, fkn snake 😂
@Pekara121
6 ай бұрын
@@uniquetobin4realthis person really said "it's cool when things are complicated and not simple 😃" like what?? 😂
@F14_Tomcatter
5 ай бұрын
Such thing is seems near impossible in this simple scenario, demonstrate it if you think that you are true.
@EWILD99
4 ай бұрын
@@F14_Tomcatter the fact that the code runs in about 4 seconds when you run it not 1 minute because he ran a precompiled C file, but the python file wasnt so it compiled then ran. if you run it a second time it is about 4 seconds as tested
@MrRjizz
4 ай бұрын
@@EWILD99 i remember implementing the dutch flag problem for large suffix arrays for a algorithm course i had and running one large sample set that would take like 3.0s on java would take the python code like a hour.
I think if you use -o2 while compiling c++ it will be more optimized
@uwirl4338
Жыл бұрын
Unlikely to make a huge difference in this simple of a program
@wrnlb666
Жыл бұрын
@@uwirl4338 no, with O2 optimization, the compiler will just set n to 1 billion before the while loop. To truly optimize the code, he can add a register keyword when declaring n, that will make the program runs 4 times faster on my pc
@taragnor
Жыл бұрын
@@wrnlb666 Oh really? I was under the impression the register keyword didn't even really do much on modern C/C++ compilers and was more a relic of the past, since modern compilers are so much better at optimizing now.
@target844
Жыл бұрын
@@uwirl4338 -O2 will make an enormous difference. The optimizer can and will realize that the end value of n does not depend on anything unknow at he time of complication that can change so it can be precalculated. If you look at the generated assembly -O2 will eliminate the loop completely. I tested the code on godbolt with the option and -O0 takes 3 seconds compared to -O2 at 30 microseconds. It is an optimization of a factor of 100,000, so an enormous difference. That is a runtime measure in the program around all of the code shown in the video so any startup time is not included. If iI ht optimized variant measure time to before the value is printed the time I get is 0 µs. So the 30 microseconds is the time to print the result. If you add the volatile keyword for n it can be optimized away and you get 3s gain regardless of -O0 or -O2.
@wrnlb666
Жыл бұрын
@@taragnor compiler optimization optimize things that doesn't make the result looks different. In this case, setting n to 1 billion before the while loop doesn't make the result different. Because n is not volatile, and the compiler knows that it will not be changed outside of the program.
Bro which code editor you are using? Please tell me😮.
@tienbui2814
2 ай бұрын
It’s vim
As a software engineer for the past 35 years I have found that the different computer languages are a tradeoff of speed of writing the program versus the speed of running the program. Interpreted languages like Python are great for quick and dirty one-time programs but you wouldn't want to write a Python program that mines Bitcoins.
@chloe-un9cn
4 ай бұрын
personally i wouldnt want to write any program that mines bitcoins
Addendum: For some machines, C/C++ simple loops as shown are more fast if you add one or more (try it yourself) "nop" instruction into the loop. It may appear bizarre but can be easily explained: because the instructions alignment and CPU's execution pipeline. Eg.: #include int main() { size_t n = 0; while (n++ asm( "nop;" "nop;" "nop;" ); ; std::cout
@TheBuilder
8 ай бұрын
good idea but not something people should be doing by hand
@NikPower-gs6hs
5 ай бұрын
@@TheBuilderif the compiler would not eliminate the loop completely then it would add nops with strong optimization and I can tell you that from experience
@NikPower-gs6hs
5 ай бұрын
arguably inline assembly might be a cheat in Cpps favor but yes it would be much better on newer processors not only because of the pipeline but also because of the instruction fetching from memory reading multiple bytes per clock cycle which lead to filling the pipeline itself
now do it with JavaScript
also depends on what your running it on
If you set a constant for 1,000,000,000 does that impact performance?
Python is a relevant language for some tasks, but it’s main claim is it’s a modern interpreted language - easy to teach. A few years ago, it would have been BASIC, compiled BASIC, then Pascal. Java tried to slide in, but was pigeonholed for slow web applications. Things have to move forward, just like C, C++ and so on.
@user-td8mm1sy3j
7 ай бұрын
«««slow web applications»»»😁😁😁 Then what is not in your opinion?
Nobody just counts- except to understand the overhead. The things I would do at each increment are probably written in C, and likely designed to run on a GPU. I use python to execute functions in libraries. These are likely to be faster implementations of code than I could write in any language simply because they are typically open source and have lots of eyes on them. Was that the point- python is slow at loops?
if you use a for loop, it ran (on my computer) in 44 secs. for x in range(1_000_000_000): n = 1 print(x)
Did you include the time it took to write? Or compile?
@TheBuilder
Жыл бұрын
its in the video if you want to count it. i only sped up the execution of pythons code
Well you should always use the for with range in python if you can. Since that is C under the hood (in python 3). So kinda misleading. For more info look at m_coding’s video
@Ruchunteur
Жыл бұрын
It still slow though. I tried this: ``` n = 0; for _ in range(1_000_000_000): n+=1 print(n) ``` and it took 1m38s to finish
@joytimmermans
Жыл бұрын
@@Ruchunteur That is true, but it is faster then the while loop, you can even speed it up more with pure python to just use build in functions instead of using the for looping. max(range(1_000_000_000) speed is up from 1m30sec to 19sec. you can then speed this up more with numpy but also you can speed it up more with just math and seeing that the highest one will be 1_000_000_000 and then just print 1_000_000_000 making it run in 0.5 sec. would reccomend the mcoding video kzread.info/dash/bejne/g5uZ2NtwZcbVaMY.html for a explanation. but yea that is the dangers with python it can get really really slow if you dont know what you are doing
I got 46 seconds using a while loop and 43 seconds using a for loop in python3.10.6.
@leosmi1
Жыл бұрын
Try 3.11
@alejandrosrwebmaster
Жыл бұрын
try C
have you tried constexpr in c++?
What’s up with the high commas?
Idk whether it's still the case but Pypy (a python interpreter designed for speed) used to beat C++ on some regular expression benchmark (basically C++ had to redo all the work for every iteration whereas the JIT could hardwire the regular expression and optimize it).
@asuasuasu
Жыл бұрын
if the comparison was against std::regex, then that's no surprise, because std::regex is hilariously slow. like, "outperformed by literally any other option" slow. CTRE would be a different story, though :) tracing JITs are interesting tech though! there are definitely cases where it would be totally expected to trash an AOT compiler's optimizations.
@cmilkau
Жыл бұрын
@@asuasuasu JIT shine when you have data that is constant in practice but variable in theory. Like, matching repeatedly against a fixed regex. A precompiled regex lib has to analyse the regex every time. A JIT can compile a short program that represents the regex.
@donovan6320
Жыл бұрын
@@cmilkau but also std::regex is slow and you should never really use it.
@alanramirezherrera7485
6 ай бұрын
@@cmilkau C++'s std::regex is not a good choice (nor a good way to benchmark C++ vs anything else), it is slow due to it's design, almost anything outperforms it.
@maanavsingh1914
5 ай бұрын
@@cmilkau you can harness similar optimizations on compiled languages using PGO with a modern compiler to generate more optimized machine code for your input space.
The thing is that the C++ compiler will understand the loop and optimise on its own. -O3 does the trick. The loop will not even be generated as machine code. check compiler explorer.
I'm new to this, but how much faster would an assembly language be than c++?
@TheBuilder
Ай бұрын
the C++ compiler generates assembly, so it's not much of a comparison, unless you're using specialized instructions which your compiler is not aware of
Does Python count it in a default speed that unless specified, is slow? Or is it just that bad?
@TheBuilder
Ай бұрын
if you want to count in python using the standard interpreter in the standard way, yes it's that slow.
I would point out that while loops are actually slower than for loops in python, but i guess its fair because you used while loop in c++ too.
@vadiks20032
Жыл бұрын
why are they slower wtf
@tipoima
Жыл бұрын
@@vadiks20032 Probably something gets optimized if the compiler knows how long the loop will run for. Then again, I also heard that all for loops in python are while loops under the hood
@monochromeart7311
Жыл бұрын
In python, while-loops are faster than for-loops. Python's while-loops are exactly like C while-loops, but Python for-loops are more complex and contain more overhead. Python's for-loop has to call "next()" on an object to fetch the next value, but "next()" tells you it doesn't have any more values using an exception which has to be caught and used to break out of the for-loop. It can be implemented using a while-loop and a try-except block.
@AnimatorArt24
Жыл бұрын
@@monochromeart7311 In python, while loops are slower. stackoverflow /questions/1377429/what-is-faster-in-python-while-or-for-xrange
@monochromeart7311
Жыл бұрын
@@AnimatorArt24 that's a stackoverflow question from 13 years ago, about Python 2's xrange. Python 3 doesn't have xrange anymore, and the language went through many changes in 13 years.
You can do a for loop instead in Python to optimize it even further
@markpozsar5785
6 ай бұрын
Or don't ask python to do things it isn't meant to do
If you were to properly built that with optimizations it would be instant since the compiler will work out you're not actually doing anything and just handle it compile-time. Clang is very good at that. You can enforce it by using a constexpr function to do the counting.
Olá! Qual IDE você usou para programar? Vlw pelo vídeo!
@heroe1486
Жыл бұрын
If you ask about this video that's vim, it's a text editor not IDE, although you can bring IDE functionalities via plugins
@TheBuilder
Жыл бұрын
Honestly I don't recommend Vim for writing code, just use Visual Studio and take it easy
In C++ u can use ++n as probably the fastest way to increase varlue by 1. Also for loop can be faster. Python for loop is runnig C for loop so it would be much faster.
@zephor6664
6 ай бұрын
Why would ++n be faster? It's still the same assembly instructions right? Isn't it just returning before the other instructions?
@decode9242
6 ай бұрын
@@zephor6664 It may be faster, since i++ usually cannot be implemented without an intermediate copy, but ++i is done in place and returns a reference to itself.
@vladimirarnost8020
6 ай бұрын
@@decode9242 Both ++i and i++ produce the same INC instruction for integers. There is no difference. If you take their value, e.g. x = ++i; vs x = i++, then there is a difference of _when_ the value if i is copied to x but i is still simply incremented if it resides in a register in most cases. Depending on the context, the compiler might also use a LEA instruction to perform the arithmetic if it deems it beneficial. Where the prefix vs. postfix notation _may_ make difference is with C++ iterators. It's generally preferable to use the prefix form, i.e. ++it. If the ++operator is inlined, even the postfix form might actually result in identical code if the value of it++ is not used anywhere, the temporary copy is optimised away. It depends on many factors, including the compiler type, version, CPU type, register size, surrounding code, etc.