Ruby Get Started with TruffleRuby

42thcoder for 火铺 · October 29, 2018 · Last by 42thcoder replied at October 30, 2018 · 1885 hits

TruffleRuby 最近发布了 truffleruby-1.0.0-rc8, 离运行完整的 Rails 应用已经很近了,值得一玩。记录一下过程,给大家做个参考。

安装 TruffleRuby

目前已经支持 rbenv 和 rvm, 比之前手动构建方便了很多。我这边的系统是 macOS Mojave, 兼容性还不错。

确保先安装 Java, 版本大于 8, 可以直接安装 11, 多版本并存的话推荐 jenv

  • brew upgrade rbenv && brew upgrade ruby-build
  • rbenv install truffleruby-1.0.0-rc7
  • rbenv local truffleruby-1.0.0-rc7
  • gem install bundler
  • ruby -v => truffleruby 1.0.0-rc7, like ruby 2.4.4, GraalVM CE Native [x86_64-darwin]`

尝试 Sinatra

先跑个简单的应用:Simple Sinatra App .

  • gem install sinatra
  • gem install puma, 用 puma 来跑,更符合实际情况
  • bundle exec puma config.ru

打开浏览器,转到 localhost:9292 就能看到了。

性能

用 wrk 简单测试了一下,wrk -c 10 -t 5 -d 10 http://localhost:9292, 性能有点差。比 MRI 慢了一半,反馈给官方,官方的意思是目前专注于运行完整的 Rails 应用,性能问题后面再说。

MRI

Running 10s test @ http://localhost:9293/
  5 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     8.29ms    9.80ms 145.37ms   96.30%
    Req/Sec   277.99     51.06   380.00     78.00%
  13866 requests in 10.03s, 2.45MB read
Requests/sec:   1383.02
Transfer/sec:    249.95KB
TruffleRuby
Running 1m test @ http://localhost:9292/
  5 threads and 10 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   144.61ms  321.44ms   1.87s    88.72%
    Req/Sec   134.63     80.87   410.00     63.68%
  30442 requests in 1.00m, 5.37MB read
Requests/sec:    506.60
Transfer/sec:     91.52KB

尝试 Rails

gem

完整运行 Rails 的最大挑战来源于在 JVM 中跑 C 扩展,而 Ruby 这么多年来也没有统一的 C 扩展 API, 太多 gem 都是基于 MRI 的内部机制来开发,只能一个个适配。目前最大的两个 gem: 一个是 nokogiri, 一个是 mysql2.

目前来说 nokogirisqlite 的组合是没有问题的,mysql2 还在开发中。

  • gem install nokogiri -- --use-system-libraries
  • rails new simple-rails-app

如果此处提示 Gemfile not found, 可以尝试运行 gem update

代码

创建的项目,直接运行的会有问题,要做几个调整。

config/boot.rb:4bootsnap 注释掉,暂时不支持。在 Gemfile 中增加两个 gem: gem 'concurrent-ruby', '1.1.0.pre2',require:'concurrent'gem 'listen'

之后就是常规操作了。bundle exec rails g scaffold post title:string content:text; bundle exec rails db:migrate; bundle exec rails s.

打开浏览器,转到 localhost:3000/posts 就能把酷炫的博客系统跑起来了

性能

简单试了一下,性能也不乐观。期待正式版了。

备注

看完文章,可能会对 TruffleRuby 的性能不满,但实际上单看语言运行的话还不错的。大家可以跑跑 fib 试一下,跑热之后还是可以跟 nodejs 拼一下的。

启动速度比 MRI 慢不少,但是基本上可以接受。

性能比 MRI 慢?都是用的 puma 作为 app server 吗?

Reply to nouse #0

都是 puma, 跑热之后,差距会变得比较小,但是相比 MRI 还是没有优势。

42thcoder closed this topic. 29 Oct 16:14
42thcoder reopened this topic. 29 Oct 16:15
Reply to nouse #4

TruffleRuby 透过 LLVM ; Sulong 也可以直接执行 C. 所以也不能完全说是作弊。

Chris Seaton 在 Reddit 也说过最后这个阶段难度及时间需要比他想像中多。

Reply to nouse #4

不能算作弊啊,高性能跑 C extensions 是 TruffleRuby 的卖点之一。

毕竟也是吹过 🐂 的。

We run existing Ruby C extensions and show how our system executes combined Ruby and C modules on average over 3X faster than the conventional implementation of Ruby with native C extensions,

You need to Sign in before reply, if you don't have an account, please Sign up first.