游戏框架:异步VS同步性能 [英] Play Framework: Async vs Sync performance

查看:376
本文介绍了游戏框架:异步VS同步性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code:

  def sync = Action {
      val t0 = System.nanoTime()
      Thread.sleep(100)
      val t1 = System.nanoTime()
      Ok("Elapsed time: " + (t1 - t0) / 1000000.0 + "ms") 
  }

  def async = Action {
    val t0 = System.nanoTime()
    Async { 
          Future{
            Thread.sleep(100)
            val t1 = System.nanoTime()
            Ok("Elapsed time: " + (t1 - t0) / 1000000.0 + "ms") 
            }   
    }
  }

以上code之间的区别是,同步会睡接受请求,并异步将睡在单独的线程所以负责接待的请求的线程可以继续接受请求,而不会阻塞的线程上。当我轮廓线,我看到在异步请求创建为预期的线程数量突然增加。然而如上文4000并发连接20秒斜坡结果在相同的吞吐量和延迟这两种方法。我期望异步有更好的表现。为什么会这样呢?

Difference among above code is that sync will sleep on the thread that received request and async will sleep on the separate thread so that thread in charge of receiving a request can keep on receiving requests without blocking. When I profile thread, I see a sudden increase in number of threads created for async requests as expected. However both methods above with 4000 concurrent connection 20 sec ramp result in the same throughput and latency. I expected async to perform better. Why would this be?

推荐答案

简短的回答是,这两种方法在本质上是一样的。

The short answer is that both methods are essentially the same.

行为本身始终是异步的(参见处理异步结果 文档)。

Actions themselves are always asynchronous (see documentation on handling asynchronous results).

在这两种情况下,睡眠呼叫动作的线程池发生(这是不是最优的)。

In both cases, the sleep call occurs in the action's thread pool (which is not optimal).

了解播放线程池

游戏框架,从下往上,异步Web框架。流使用异步处理iteratees。在播放线程池调整使用较少的线程比传统的web框架,因为IO在发挥核心不会阻塞。

Play framework is, from the bottom up, an asynchronous web framework. Streams are handled asynchronously using iteratees. Thread pools in Play are tuned to use fewer threads than in traditional web frameworks, since IO in play-core never blocks.

由于这个原因,如果你打算写阻塞IO code或code,它可能做了很多的CPU密集型的工作,你需要知道到底哪个线程池是轴承的工作负荷,而你需要调整它相应。

Because of this, if you plan to write blocking IO code, or code that could potentially do a lot of CPU intensive work, you need to know exactly which thread pool is bearing that workload, and you need to tune it accordingly.

例如,这个code片段使用一个单独的线程池:

For instance, this code fragment uses a separate thread pool:

Future {
  // Some blocking or expensive code here
}(Contexts.myExecutionContext)

随着更多的资源,请参阅这个答案并的有关详细信息,该视频上处理异步操作和的这个并的这个论坛消息关于这个问题的广泛讨论。

As additional resources, see this answer and this video for more information on handling asynchronous actions and this and this forum messages for extensive discussions on the subject.

这篇关于游戏框架:异步VS同步性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆