Speed Up Your Code With Cython

Sdílet
Vložit
  • čas přidán 28. 07. 2024
  • Today we learn how to speed up Python code, using Cython.
    ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾
    📚 Programming Books & Merch 📚
    💻 The Algorithm Bible Book: www.neuralnine.com/books/
    🐍 The Python Bible Book: www.neuralnine.com/books/
    👕 Programming Merch: www.neuralnine.com/shop
    🌐 Social Media & Contact 🌐
    📱 Website: www.neuralnine.com/
    📷 Instagram: / neuralnine
    🐦 Twitter: / neuralnine
    🤵 LinkedIn: / neuralnine
    📁 GitHub: github.com/NeuralNine
    🎵 Outro Music From: www.bensound.com/
  • Věda a technologie

Komentáře • 129

  • @Magmurrr
    @Magmurrr Před 3 lety +135

    When using the time module to benchmark something use time.perf_counter() rather than time.time() as it provides more precision and isn't the time since the epoch!

    • @jithin.johnson
      @jithin.johnson Před 2 lety +2

      thanks!

    • @calvindibartolo2686
      @calvindibartolo2686 Před rokem

      I thought it was just a much more accurate time to the nanosecond or something?

    • @edwardb05
      @edwardb05 Před rokem +4

      ​@@calvindibartolo2686 I'm late to this but for everyone else, perf_counter_ns() does nanoseconds and perf_counter() does seconds

    • @prawnydagrate
      @prawnydagrate Před 9 měsíci

      @@edwardb05 similarly time.time_ns() does nanosecodns

    • @forgeff99
      @forgeff99 Před 10 dny

      Anyhow, cython is much faster than normal python, we don't even need to talk in nano seconds.

  • @BobBeatski71
    @BobBeatski71 Před 2 lety +6

    Here I was trying to attach Python to my C, when really I should try attaching C style to Python. 👍 Great vid. You've given me something to consider.

  • @holo23
    @holo23 Před 3 lety +41

    This is actually pretty useful
    I wasn't aware that cython was a thing until now
    Thanks for this!

  • @hyakushiki23
    @hyakushiki23 Před 2 lety +4

    Thanks again for a great video. I like that you use Windows as well.
    It was cool to see the speed of : flexibility of Python vs rigidness of cython

  • @rushas
    @rushas Před 3 lety +6

    Great video! I would love to watch more of those Cython vs Python

  • @gaelc13
    @gaelc13 Před 5 měsíci

    It's not only about static typing, but also probably about predefined vs dynamic sized array. Dynamical array size definitely comes at a cost.

  • @barendscholtus1786
    @barendscholtus1786 Před 2 lety +16

    If both functions are in the same source file, both will be compiled I assume? Have you tried putting the optimised function in a separate pyx file and only compiling that?
    Finally you might be able to do number += 2 because prime numbers cannot be even anyway.

  • @isaacbaum6745
    @isaacbaum6745 Před 3 lety +15

    This is an example of Cython working better, but how about a comprehensive tutorial on how to use it? Does it work when you're using machine learning libraries?

    • @DendrocnideMoroides
      @DendrocnideMoroides Před 2 lety +1

      well if you use it with something like NumPy which is already fast you will achive no speedup at all, if it is even possible

    • @NphiniT
      @NphiniT Před rokem

      Actually Cython is used most commonly (in my experience) in data science to speed up processor intensive tasks

    • @lbgstzockt8493
      @lbgstzockt8493 Před rokem

      Most/all machine learning libraries already use well-optimized Assembly/C++/Fortran Code under the hood, so you won`t get any speed improvements.

    • @NphiniT
      @NphiniT Před rokem

      @@lbgstzockt8493 You will get improvements for the python code you actually use. Especially for expensive tasks.

  • @b391i
    @b391i Před 3 lety +1

    All respect for you bro 🙏

  • @victordvickie
    @victordvickie Před 3 lety +1

    Will there be a follow up with C-Extension and a comparison with cython?

  • @prashanthb6521
    @prashanthb6521 Před rokem +1

    Very well explained.

  • @brucea9871
    @brucea9871 Před rokem +10

    There is a way to make your prime detecting more efficient. The only even prime number is 2 so there is no need to test the remaining even numbers. It would be more efficient to insert 2 in the list at the beginning of the program, then start testing at 3 and increment the number to be tested by 2 each time instead of by 1 as you did. This would double the speed of the program since there would be only half as many numbers to be tested. Another thing to consider is that when testing a number for primality it is not necessary to check if any prime less than the number divides it. It is only necessary to check if any prime less than its square root divides it. But I'm not sure how much this would speed up the program (if at all) due to the overhead of calculating the square root of each number to be tested (unless you used a relatively simple formula to approximate the square root instead of calculating a precise value).

    • @abhishankpaul
      @abhishankpaul Před 11 měsíci

      The sqrt n method will work faster always as the code will iterate sqrt n times. Calculating the sqrt n won't be affecting much as compared to running code for n/2 or n/4 times. For 1st few numbers, n/2 or n/4 method will dominate and that too even before the number 20. I used the sqrt n method in the super slow bash script and it accurately found that 10247693 is a prime within a second, while Python was even faster than that. Even if you scale it to find all primes over a range, the sqrt method is simplest AND fastest method to find primes

    • @jesussevillaperez3639
      @jesussevillaperez3639 Před 9 měsíci +1

      I think the point here was not how to make that particular algorithm faster, but to show the difference between regular python and cython

    • @brucea9871
      @brucea9871 Před 9 měsíci

      @jesussevillaperez3639 I am well aware of that. I just wanted to point out an improvement to the algorithm. If my suggestion was incorporated it would still show the increase in speed provided by Cython since both the Python and Cython versions would be faster.

    • @Max-fw3qy
      @Max-fw3qy Před 18 dny

      ​@brucea9871 you suggestion has no value here, he could do anything just to show the difference, it doesn't matter.....

  • @renesis888
    @renesis888 Před 3 lety +1

    How does Cython compare vs PyPy in terms of speed ?

  • @roccov3614
    @roccov3614 Před 2 lety

    Woah! What's this for-else code? Can you you use else with for loops? I'll have to look that up. Didn't know about that. Learn something every day.

  • @pakxo.
    @pakxo. Před 2 měsíci

    ty, exactly what I wanted to know.

  • @pavantippa2287
    @pavantippa2287 Před 2 lety

    Thanks u saved my day

  • @MagnusAnand
    @MagnusAnand Před 2 lety

    I love this video!!!

  • @saurabhagrawal643
    @saurabhagrawal643 Před 3 lety +2

    That's Great👍🏻

  • @TheRealKitWalker
    @TheRealKitWalker Před 3 lety +1

    Thanks dude 👏👏✌️✌️👍

  • @brandonhornick6878
    @brandonhornick6878 Před rokem

    How does he get the pyx to work. I get a message saying I can’t do it on the community version.

  • @vishnubalaji9500
    @vishnubalaji9500 Před rokem

    so whats the advantage of using cython instead of ctypes?

  • @magicpython3887
    @magicpython3887 Před rokem

    it didn't work .when i did the command 'py .\setup.py build_ext --inplace' created a new file with title 'main.c' and written "#error Do not use this file, it is the result of a failed Cython compilation.
    " init. What i need to do?

  • @anonymspro7864
    @anonymspro7864 Před 3 lety

    Bro how can i run my python file on android like Suppose i've created a clock.py file and it can run easily in computer but not in android :( please help me.

  • @JonakT
    @JonakT Před 4 měsíci

    Sir, can we make exe files of kivy program by simply naming it .pyx and compiling it?

  • @cw9249
    @cw9249 Před rokem

    i tried this but cython only created a .c file, no pyd. i cant import the compiled script

  • @RAM-im5lr
    @RAM-im5lr Před 3 lety

    Please create a video on python user input in nested autocomplet

  • @JackyVSO
    @JackyVSO Před 2 lety +6

    When I do "import main" in VSCode, it says "import main could not be resolved"

  • @dhanviner1983
    @dhanviner1983 Před rokem

    NameError: name 'exit' is not defined
    my exit command gives me this error. How can I fix it?

  • @stevehageman6785
    @stevehageman6785 Před 6 měsíci

    Thanks for the 'starter'. :-)

  • @cadowyn735
    @cadowyn735 Před 3 lety

    Is there a Cuby?

  • @cyanuranus6456
    @cyanuranus6456 Před rokem

    First I Love C# and Python. Now I Love Cython too

  • @mohsenhaddadi1117
    @mohsenhaddadi1117 Před 3 lety +1

    The question is, do built-in python functions ;like count method for lists; use Cython?
    and if the answer is yes, is it much faster to use count method instead of using for loop in a list?

    • @cadowyn735
      @cadowyn735 Před 3 lety

      My general understanding is that built in methods would be faster. Not sure about the Cython though

    • @savageautomations
      @savageautomations Před 3 lety

      A lot of built in stuff is optimised, not sure about count though

    • @jagaya3662
      @jagaya3662 Před 3 lety +1

      I mean, you could just test it out ;)
      But generally: Yes, built-in functions and functionality is at least optimized but often written in C. So it will easily outperform anything you write in Python yourself.

  • @totalpieceofhit6100
    @totalpieceofhit6100 Před rokem +2

    Why [p for p in primes[:found]] instead of just primes[:found] you're literally iterating through each number of a list, putting it in another list and returning the new list. (?!?!?!?!)

  • @alexandermylnikov7774
    @alexandermylnikov7774 Před 3 lety +2

    shouldnt you initialise the primes array to size amount

    • @kaanx4464
      @kaanx4464 Před rokem

      no, u cant initialize the size of an array in runtime, it needs to be clear what size it is in compile time. If u do it in runtime it could give you an stack overflow

  • @mad4hat
    @mad4hat Před 3 lety

    what the name of your outro song

  • @ajiteshkumar
    @ajiteshkumar Před 3 lety +8

    me: wants to know about cython because python is soo slow
    NeuralNine: I have read your mind, here you go.
    Thanks!

  • @Luc1an_
    @Luc1an_ Před 3 lety +27

    I am faster than Cython😅

  • @tjbwhitehea1
    @tjbwhitehea1 Před 2 lety +1

    Hey, what C compiler are you using for windows?

    • @Loamfy3
      @Loamfy3 Před 16 dny

      msvc (from Visual Studio Build Tools)

  • @Saimon404
    @Saimon404 Před 2 lety

    How to decompile cython to python ??

  • @zian.2493
    @zian.2493 Před 3 lety

    how to make simple program for editing photos like upscaling its resolution

    • @cadowyn735
      @cadowyn735 Před 3 lety

      Bro there’s probably quite a bit of fundamentals that go into that. Lol
      You might be able to find something online but that’s a project probably for more advanced programmers...not beginners.

  • @itaydvash
    @itaydvash Před 2 lety

    Why in prime_finder_optimized you didn't use the append method?

    • @thomasmeister8476
      @thomasmeister8476 Před 2 lety +2

      because "primes" here it is a C-array, not a python list.

  • @NamiberGames
    @NamiberGames Před 2 lety

    It's kinda dumb to ask but does cython have use cases ? Python isn't know to be optimised but then instead of using cython why not coding directly in C/C++ ?

    • @navjotsingh2251
      @navjotsingh2251 Před 2 lety +6

      Cython definitely helps when doing high priority code. For example, machine learning models can benefit from cython if it's a massive model with massive data sets.
      Moreover, Django also uses cython in the background to speed up web development, as you want your server to be fast.
      Cython pretty much compiles down to well formatted C code, almost as if a professional C developer wrote it. It does this without you having to even know C at all.

  • @EshaanIITM
    @EshaanIITM Před 24 dny

    can someone please explain why we used "100000" when defining the "primes"? Why not use something like "primes[amount]"?

    • @vi8370
      @vi8370 Před 12 dny

      In C and C++ array size must be known at compile time. amount is known only at runtime(even if we use constant in parameter when we call the function).

  • @philtoa334
    @philtoa334 Před 2 lety

    Thx.

  • @iniyan19
    @iniyan19 Před 3 lety +1

    How is it compared to vanilla c ?

    • @Louisianish
      @Louisianish Před 2 lety

      Because Cython is compiled into C code, I’d imagine they’re equivalent in speed, but I’m also curious about the answer to this question.

  • @cyanuranus6456
    @cyanuranus6456 Před rokem

    I Love Cython too Now

  • @Nittrader
    @Nittrader Před 2 lety

    it's not working on big python script's

  • @mikefocal5770
    @mikefocal5770 Před 2 lety +7

    Hi NeuralNine, great Video, can ask this question : why using Python instead of C++?

    • @linuxrant
      @linuxrant Před 7 měsíci

      because python is cool to write and readable and I hate squiggly brackets.

  • @martyrd0m
    @martyrd0m Před rokem +1

    make a tutorial on compiling .pyx to .c to .exe. The executable should run without any dependencies

  • @s.aravindh6227
    @s.aravindh6227 Před 3 lety +3

    Import turtle 🐢 small tutorial video bro 👍👍👍👍

  • @mimurajam1501
    @mimurajam1501 Před 3 lety

    nice video

  • @kritagyagupta9356
    @kritagyagupta9356 Před 2 lety

    Subbed

  • @dipeshsamrawat7957
    @dipeshsamrawat7957 Před 3 měsíci

    Thanksgiving 💯

  • @allenanderson4179
    @allenanderson4179 Před 3 lety

    What IDE are you using?

  • @zombiekiller7101
    @zombiekiller7101 Před 3 lety

    Nice

  • @abdellasolomon6244
    @abdellasolomon6244 Před 3 lety +3

    Very nice tutorial.
    please also make an Iron python tutorial.
    thanks.

  • @djscratchcat474
    @djscratchcat474 Před rokem

    When the language is so slow you have to use c code to make it bearable

  • @abhinavchoudhary8014
    @abhinavchoudhary8014 Před 3 lety +7

    I learnt many things
    But I had a request to plz make a short playlist for these types of all modules which can useable for python
    Plz teaches us cython syntax and all stuff in detail as well as pandas and numpy
    I want to learn those thing
    Plz sir

  • @arnavmehta3669
    @arnavmehta3669 Před 3 lety

    Can opencv and cython combined?

    • @ckalas
      @ckalas Před 3 lety +2

      the thing is most computational libraries already call their own c/c++ code, things like numpy / opencv / tensorflow etc all are already optimized internally

  • @hectorminator4
    @hectorminator4 Před 3 lety +6

    Yeah, you can also work with numpy arrays instead of regular lists and it will work much faster without all the need of that c complexity sintax, but great video anyway, I'll search about this way of programming

    • @navjotsingh2251
      @navjotsingh2251 Před 2 lety +2

      Numpy is a C library, certainly knowing cython and C can help you extend numpy and heck even make it faster if you're running into problems you can program it at the C/Cython level to make optimizations.

  • @atwork22
    @atwork22 Před rokem

    Wow!!!

  • @troeteimarsch
    @troeteimarsch Před 2 lety

    nice videööööö :) grüße ;)

  • @samlolpip1604
    @samlolpip1604 Před 3 lety

    Soooooooooo gret video pls make a lot of video about discord boy tnx

  • @adrienc8716
    @adrienc8716 Před rokem

    Pyd is for Windows. How do we do for Linux ?

    • @Loamfy3
      @Loamfy3 Před 16 dny

      Compile it on Linux system or use WSL (Windows Subsystem for Linux)

  • @Julian-xc4fk
    @Julian-xc4fk Před 7 měsíci

    11:24 break my focus hahaah

  • @hugopristauz3620
    @hugopristauz3620 Před 7 měsíci

    cool

  • @Dbdlkxbdbwk
    @Dbdlkxbdbwk Před 3 lety +2

    Which code editor are you using ?

  • @mechaelbrun-kestler3868
    @mechaelbrun-kestler3868 Před 3 lety +4

    The one complaint I had with Python was the type ambiguity.

    • @barendscholtus1786
      @barendscholtus1786 Před 2 lety +1

      You can provide your type annotations in your python code, mypy can perform the linting, and your IDE the code analysis.

  • @guilherme5094
    @guilherme5094 Před 3 lety

    Like!

  • @magic_2942
    @magic_2942 Před 3 lety +1

    Personally I don't like Cython, If you want to speed up your python just use numba and with just one decorator you are set to go, and I would rather use Rust and bind it with python with pyo3 rather than using Cython

  • @TachBox71jr
    @TachBox71jr Před 5 měsíci

    How To decoded Cython

  • @GCKteamKrispy
    @GCKteamKrispy Před rokem

    So it's just Rust?😅

  • @BehruzZoirov-if5kw
    @BehruzZoirov-if5kw Před 2 měsíci

    Python cython 😅😂😂😂😂

  • @koooravevo8294
    @koooravevo8294 Před rokem +1

    You made the optimized takes min of 1000 and amount
    So in case you pass amount higher than 1000 it will always take the 1000
    So all your work is like nothing and not practical at all

  • @saihitesh5816
    @saihitesh5816 Před rokem

    why don't my pycharm accept .pyx ? it is just reading it as a text file

  • @calypso1441
    @calypso1441 Před 3 lety

    mach mal videos auf deutsch auch

  • @navinvenkatesan9784
    @navinvenkatesan9784 Před 3 lety

    Bro telegram bot

  • @crystal_royal3405
    @crystal_royal3405 Před 3 lety

    Just use cpp lol

  • @XyndraNerd
    @XyndraNerd Před 3 lety +1

    second

  • @ZenthmYT
    @ZenthmYT Před 2 lety

    Me #1k likes

  • @monstertruck6612
    @monstertruck6612 Před 2 lety

    Take regain with cold drink CO2 mix inject method in detal arm be young again

  • @stevenhe3462
    @stevenhe3462 Před 2 lety

    Horrible program
    Great demonstration of Cython

  • @SylwesterKogowski
    @SylwesterKogowski Před 3 lety

    Omg, why don't you just program in language that is appropriate to the application.
    If you really need so fast module, make a library in c or even assembler if necessary.

  • @undeadpresident
    @undeadpresident Před rokem

    I can't get this to work. Says there's a syntax error in _distutils_hack\__init__.py