EventMachine的优势是什么 [英] what is the advantage of EventMachine
问题描述
这是我的测试用例,我发现EM并不比一般的TCP服务器快
This is my test case, I found that the EM is not faster than the general TCP server
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:快速且可扩展的事件驱动 I/O 框架
Simplicity compared to threads, not speed. Look here for more insights: EventMachine: Fast and Scalable Event-Driven I/O Framework
适用于您的问题的引文:
The citation that applies to your question:
关于事件驱动程序在理论上并不比线程程序快的事实已经写了很多,这是真的.但在实践中,我认为事件驱动模型更容易使用,如果您想获得极高的可扩展性和性能,同时仍确保最大的健壮性.我编写的程序必须运行数月或数年而不会崩溃、内存泄漏或表现出任何类型的性能不稳定,因此在实践中,事件驱动编程效果更好.现在,这是事件驱动编程的问题:您必须向后"编写.线程模型将您的程序状态(低效地)存储在运行时堆栈上的局部变量中.在 EM 中,你必须自己做这件事,这对于习惯于线程的程序员来说是非常不直观的.这就是我对纤维感兴趣的原因,因为它开启了编写程序员看起来像阻塞 I/O 的可能性,但仍然是事件并且不使用线程.
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.
这篇关于EventMachine的优势是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!