Async Techniques and Examples in Python Transcripts
Chapter: Parallelism in C with Cython
Lecture: Cython syntax compared

Login or purchase this course to watch this video and the rest of the course contents.
0:00 I'm guessing most of you have never written Cython code. You might not even know what Cython code looks like. Maybe if you saw it you could tell me
0:10 okay, I think that's not Python, it might Cython but it turns out the language is slightly ever so slightly different. So, let's look at its syntax.
0:17 And here's the example we're going to work with. We're going to do some computational stuff here. The function is called do_math.
0:24 It takes a start and the number of times it's going to increment from there. And we've seen this before when we did our threading
0:30 and our multiprocessing. It's just a silly math function that does useless math but it lets us do performance testing
0:36 and parallelism testing and things like that. It's using Python 3.5's type annotations. So, up there we have start:, num: and so on
0:45 but of course we could omit those and things will still work just the same. Right, so this is pure Python, this is not Cython.
0:51 I'm going to show you this function converted over to Cython. You ready? Keep your eye on it. There's the Cython. There's Python. There's Cython.
1:02 Two changes, one, we have more type annotations so start in the argument there is no longer an integer it's a Cython int.
1:11 In Python, in CPython, integers and numbers and stuff they're still basically objects on the heap. They're not allocated on the stack as four bytes
1:19 or eight bytes or whatever the size of these are. They're actually allocated in the heap and there's pointers, and that really slows down math
1:26 and adds a lot of overhead. So we can explicitly say that start and num are Cython integers
1:31 and that means they're going to be allocated on the stack in C. And then we have three local variables
1:36 which we had before but we didn't explicitly say the type. Here we're saying explicitly that's a cython.float. cython.float, cython.float.
1:43 And then, we're doing our while loop exactly the same. So that's the only change. We've done a little bit of type annotations
1:51 and we're using a more high performance square root. We were using math.sqrt before which is Python's standard library.
1:58 Fine, and that would still work in Cython but it turns out to be slower and it prohibits one of the techniques we want to apply later.
2:05 So we have this libc.math that actually has sqrt and a bunch of other math operations that you might want to do.
2:12 So we're going to use Cython's built-in more high performance math operation. That's it. I'll flip back and forth a couple times for you one more time.
2:22 Just notice, just a few more type decorations and a different square root. Pretty sweet, right?

Talk Python's Mastodon Michael Kennedy's Mastodon