gpt4 book ai didi

ruby - EventMachine的优势是什么

转载 作者:可可西里 更新时间:2023-11-01 02:37:43 28 4
gpt4 key购买 nike

这是我的测试用例,我发现EM并不比一般的TCP服务器快

EM 服务器:

    require 'rubygems'
require 'benchmark'
require 'eventmachine'
class Handler < EventMachine::Connection
def receive_data(data)
operation = proc do
# simulate a long running request
a = []
n = 5000
for i in 1..n
a << rand(n)
a.sort!
end
end

# Callback block to execute once the request is fulfilled
callback = proc do |res|
send_data "send_response\n"
end

puts data
EM.defer(operation, callback)
end
end

EventMachine::run {
EventMachine.epoll
EventMachine::start_server("0.0.0.0", 8080, Handler)
puts "Listening..."
}

和我的基准测试:

require 'rubygems'
require 'benchmark'
require 'socket'
Benchmark.bm do |x|
x.report("times:") do
for i in 1..20
TCPSocket.open "127.0.0.1", 8080 do |s|
s.send "#{i}th sending\n", 0
if line = s.gets
puts line
end
puts "#{i}th sending"
end
end
end
end

最佳答案

与线程相比简单,而不是速度。在此处查看更多见解:EventMachine: Fast and Scalable Event-Driven I/O Framework

适用于您的问题的引文:

A lot has been written about the fact that event-driven programs are not theoretically any faster than threaded ones, and that is true. But in practice, I think the event-driven model is easier to work with, if you want to get to extremely high scalability and performance while still ensuring maximum robustness. I write programs that have to run for months or years without crashing, leaking memory, or exhibiting any kind of lumpy performance, so in practice, event-driven programming works better. Now, here's the problem with event-driven programming: you have to write "backwards." A threaded model stores your program state (inefficiently) in local variables on a runtime stack. In EM you have to do that yourself, which is very unintuitive to programmers who are used to threads. This is why I'm interested in fibers, because it opens the possibility of writing what looks to the programmer like blocking I/O, but still is evented and uses no threads.

关于ruby - EventMachine的优势是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5830147/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com