136 points · by justinhj · 8y ago · 95 comments
On a 3GHz (3 billion hertz) processor, you expect to be able to context switch billions of times per second?
I would probably accept millions without question, even though that might be pushing it for a GIL-ed runtime like Ruby has. But, unless your definition of "context switch" counts every blocked fiber that's passed over for a context switch as being implicitly context switched to and away from in the act of ignoring it, I find this hard to believe.
It takes more than one clock cycle to determine the next task that we're going to resume execution for and then actually resume it.
import time
import asyncio
REPS = 1_000_000
async def coro():
for i in range(REPS):
await asyncio.sleep(0)
t0 = time.time()
asyncio.run(coro())
dt = time.time() - t0
print(REPS / dt, 'reps/s')See: https://repl.it/repls/GrimyChiefGame
package main
import (
"fmt"
"time"
)
func coro(reps int) {
for i := 0; i < reps; i++ {
go time.Sleep(0 * time.Nanosecond)
}
}
func main() {
REPS := 5000000
start := time.Now()
coro(REPS)
dt := time.Since(start)
fmt.Printf("The call took %v to run.\n", dt)
fmt.Printf("REPS / duration %v\n", (REPS*1e9)/int(dt))
}if I remember correctly, Go's scheduler has a global queue and a local queue per worker thread, so when you spawn a goroutine it probably has to acquire a write lock on the global queue.
Allocating a brand new goroutine stack and doing some other setup tasks has a nontrivial overhead that has nothing to do with context switching, regardless of global locks.
To properly benchmark this, I think I would start with just measuring single task switching by measuring how long it takes main to call https://golang.org/pkg/runtime/#Gosched in a loop a million times. This would measure how quickly Go can yield a thread to the scheduler and have it be resumed, although this includes the overhead of calling a function.
Then I would launch a goroutine per core doing this yield loop and see how many switches per second they did in total, and then launch several per core, just to ensure that the number hasn't changed much from the goroutine per core measurement.
Since Go's scheduler is not bound to a single core, it should scale pretty well with core count.
I might run this benchmark myself in awhile, if I find time.
X = 1_000_000
f = Fiber.new do
loop { Fiber.yield }
end
t0 = Time.now
X.times { f.resume }
dt = Time.now - t0
puts "#{X / dt.to_f}/s"
~ 780K on my machine(Single-thread hardware performance differences would not account for a factor 10)
asyncio:
import time
import asyncio
REPS = 1_000_000
async def coro():
for i in range(REPS):
await asyncio.sleep(0)
t0 = time.perf_counter()
asyncio.run(coro())
dt = time.perf_counter() - t0
print(REPS / dt, 'reps/s')
~180kasynker (https://github.com/enkore/asynker):
import time
import asynker
REPS = 1_000_000
async def coro():
for i in range(REPS):
await asynker.suspend()
t0 = time.perf_counter()
sched = asynker.Scheduler()
sched.run_until_complete(coro())
dt = time.perf_counter() - t0
print(REPS / dt, 'reps/s')
~900kThe excellent curio (https://github.com/dabeaz/curio):
import time
import curio
REPS = 1_000_000
async def coro():
for i in range(REPS):
await curio.sleep(0)
t0 = time.perf_counter()
curio.run(coro())
dt = time.perf_counter() - t0
print(REPS / dt, 'reps/s')
~180kNot that this number is hugely important.
Update: I wrote an addendum https://www.codeotaku.com/journal/2018-11/fibers-are-the-rig...
It's sloppy wording either way.
Update: I wrote an addendum https://www.codeotaku.com/journal/2018-11/fibers-are-the-rig...
He might have mis-phrased it though. Maybe he meant to say that it can handle billions of concurrent tasks maybe not that they can switch rapidly in just a second xD
Not really, if you just implement a round-robin scheduler and if none of the fibres are actually blocked (i.e. if they just yield).
Artificial benchmark? Sure. But there's no way you could ever approximate this with OS threads, even if the user-space code/threads themselves do no useful work.
So as you say, a simple scheduler that just walks a linked-list could resume a stackful coroutine in a few instructions, plus the cost of restoring hardware registers (which is the same cost as a non-inlined function call), and the latter is easily pipelined so would take fewer cycles than instructions.
In the end there's a GIL. For pure CPU-bound workloads, your only true source of parallelism will be putting more processes into the mix, be it via forking or simply spawning more processes from scratch.
But inside a given a process, it seems to me that no matter what you do (fibers/threads), only 1 CPU can do CPU-bound work at a time.
If I was to design a high-performance Ruby solution, I'd ditch forking, threading and fibers. I'd focus instead in creating low-memory-footprint, fast-startup processes (read: no Rails!) that one can comfortably spawn in parallel, be it in a single server, or in a cluster (think k8s). Max Ruby processes count: 1 per core.
That is, for a CPU-bound task, you might be able to replace your thousand node k8s cluster with one machine running code written in a faster language (before even getting into communication and load balancing and HA and all that crap.)
It's probably a more sensible idea to use a native extension to optimize just that hot path. For instance, the Rust bindings are really good: https://github.com/tildeio/helix
Grinding another 5x out of a flat profile can be hard work requiring more creativity and producing less readable code than a (fairly mechanical) translation. Luckily these tasks also tend to crop up when design has stabilised and team sizes are increasing, meaning it can often coincide with the benefits of static typing becoming greater.
It's not a panacea, and it's obviously both risky and costly. Shrugs.
(I've also seen the other case, FWIW. Wrote some C extension code called from a Rails app, and it was the right call at the time and we got great mileage out of it.)
But this is beyond the scope of the article.
Parallelism is a way to have more than one execution context execute simultaneously. In a system with a GIL, it only makes sense for contexts mostly waiting for I/O. CPU-bound tasks are obviously sequenced and limited by GIL access, and no parallelism is possible.
The title as posted is most definitely not true. I have worked on high volume Ruby applications where the problem with using async I/O combined with poor raw execution of Ruby code resulted in excess garbage to be collected. Ruby performance should mean the performance of executing Ruby code. Perhaps the title could have been 'Ruby webapp performance'.
What async I/O approach did you use and where did the garbage come from? I/O buffers?
I disagree that 'minimal changes to existing code' is a good goal for a Ruby parallelism solution. The large Ruby codebases I have dealt with have gigantic hacks to get around the GIL: complex fork management systems, subprocess management, crazy load-this-but-not-that systems for prefork memory management to optimize copy on write, and probably more. Parallel tasks in Ruby are a nightmare to work with.
Changing existing code _should_ be a goal of any Ruby parallelism solution. If we can't get rid of this kind of cruft, what are we even doing?
I still love Ruby, but I want go-style channels, not apologies for the GIL.
These are the slides for Koichi Sasada’s RubyConf 2018 (last week) talk updating the community on his progress in the design and implementation of Guilds.
Surprising that the author isn’t aware of this planned CRuby feature announced in 2016. I wrote about it then: https://olivierlacan.com/posts/concurrency-in-ruby-3-with-gu...
Take this with a grain of salt of course because the design has clearly changed since then and I need to upgrade my post or do a follow-up.
Guilds felt omitted in your post since they (should) address one of the points you make about the usability/ergonomics of existing Ruby APIs for managing non-sequential execution.
But it’s definitely a bit early to tell what Guilds will actually look like as a final product.
It doesn't really imply anything about how parallel (or not) the fibers execute.
> It doesn't really imply anything about how parallel (or not) the fibers execute
What's all the fuss about paralllelism in the article about then?
Any time you call a blocking function that the system provides, it should immediately yield the fiber, which makes it look preemptive. If you write a loop that just spins forever, that could block the whole system, potentially, making the abstraction leaky. In a language like Ruby, they could definitely add some true preemption, but I don't know if that's what they plan to do.
From the article: "Fibers, on the other hand, are semantically similarly to threads (excepting parallelism), but with less overhead." So, the author definitely isn't implying parallelism of the fibers.
> What's all the fuss about paralllelism in the article about then?
The author was talking about different methods for handling more than one request at a given time, which include forking and threads. With Ruby's GIL, threads are a lot less attractive than they could be. A good fiber implementation can handle tons of network requests concurrently and very efficiently even on a single core, which is the case being discussed here.
At the end, the author discusses a hybrid approach of forking and fibers, where each processor core would have a fork of the Ruby program running, and each fork would have its own fiber pool, running many tasks concurrently.
In languages that don't have a GIL, forking is rarely a tool that I reach for. It really hurts your database pooling and all sorts of other small problems, but it's a common trade-off when using Ruby, Python, and Node.
I could be wicked wrong though, it's been a long while since I futzed with fibers.
It ought to compile pretty cleanly, since a continuation can end up being compiled into an address.
That being said, I'm sure there are different ways to implement it and I look forward to proposed faster/efficient implementations.
BTW I am in no way involved in the development of the Felix. Its not a new language, its more than 15 years old and has had fibers from the start.
I asked in https://www.reddit.com/r/ProgrammingLanguages/comments/9xsya... and get a nice answer but is also of the style "just read this code and get it".
There are quite a lot of other small differences as well since Ruby fibers are always run on the same thread which originally spawned them, whereas Loom's continuations and fibers can be resumed on a different thread.
It is quite possible to implement Ruby fibers in terms of Loom's continuations, and we've done a prototype of this in TruffleRuby (I think Charles Nutter has done one in JRuby as well), and it certainly allows us to support very large numbers of active fibers.
So if you plan on going with fiber on an existing app, double check first if Thread.current[:vars] is a must have for you & you dependencies (ex: the I18n gem
Here is an example:
fiber = Fiber.new do # Thread.current locals are copied to the Fiber when fiber it is built
puts "1. #{Thread.current[:test]}"
Thread.current[:test] = false # the fiber has it's own stack, won't leak away
puts "2. #{Thread.current[:test]}"
end
Thread.current[:test] = true
fiber.resume
puts "3. #{Thread.current[:test]}"
Output: 1.
2. false
3. true
So fibers comes with their _own stack_, including threads locals, yes, but from _when_ you instantiated them. Not from Thread.current :/ Also writing Thread.current[] won't apply outside the Fiber.I was confused, and not alone: https://github.com/rails/rails/pull/30361.
So my conclusion about Fiber is always be careful with Fiber / Thread.current.
edit: style/explanation