Coder Social home page Coder Social logo

yangwenmai / learning-rust Goto Github PK

View Code? Open in Web Editor NEW
575.0 32.0 72.0 880 KB

Rust 学习之路 > Rust Programming Tutorial, include articles, interview, example, problems.

License: MIT License

Rust 100.00%
rust rust-lang learning learning-rust tutorial tikv stargazer interview examples example

learning-rust's Introduction

Rust 学习之路

Build Status GitHub stars GitHub forks All Contributors Documentation Coverage Status GitHub issues license

Stargazers over time

Stargazers over time

learning-rust Star History and Stats

主要是对 Rust 阅读、学习,以及 Rust 相关问题讨论的总结。

阅读计划:一起学习,一起总结,一起分享!

如果想加入 Rust 学习小组的,请你搜索微信号 mai_yang ,然后备注你的姓名,公司,工作岗位职责。

你也可以直接加入 learning-rust Slack

Rust 学习过程中的问题和小贴士(Github issues)

可以查阅 Github yangwenmai/leanring-rust Issues

Rust 比 Golang 还难吗?

  • Golang 入手简单,写完后你都不知道对错,Rust 入手难,写完后 90% 都是对的。
  • 只学过 Rust 的一点点语法,晦涩难懂。

Rust 的优势在哪里?

  • 编译器很屌。
  • 没有 gc,适合高性能低延时的服务。

Rust 的应用场景是哪方面?

  • TiKV 等

Rust 有人用吗?

  1. TiKV
  2. Facebook:源代码控制工具
  3. Dropbox:在前端和后台都使用 Rust
  4. Firefox
  5. Discord
  6. Linkerd
  7. Google:作为 Fuchsia 项目的一部分
  8. 亚马逊:用 Rust 构建工具
  9. Atlassian(Jira的厂商):在后台使用 Rust
  10. 微软:在新的 Azure 物联网框架中部分使用了Rust

Rust 合作伙伴

其他:打败 Python、JS、C# 成最受欢迎编程语言,是时候掌握 Rust 了吗? - Jonathan Turner, Mozilla 工程师


Rust 学习资料

记录国内的Rust书籍与文章

Rust 入门
官方文档
《Rust By Example》中文
Learning Rust
From Go to Rust
使用 Rust 编写操作系统
Writing an OS in Rust (Second Edition) Philipp Oppermann's blog
intermezzOS, (a little OS)
《Rust 宏小册》中文
通过大量的链表学习Rust
Learn Rust With Entirely Too Many Linked Lists

更多 Rust 中文资料

Rust 书籍
Rust 编程语言-官方中文版
Rust 程序设计语言 中文版1️⃣
Rust 程序设计语言 中文版2️⃣
《Rust 编程之道》(已出版 2019.01)
《深入浅出 Rust》(已出版 2018.06)
《RustPrimer》
《Too Many Lists》:一本学习 Rust 的好书 这本书的写作风格非常的有特色, 非常适合初学者。
List of Rust Books Rust 英文图书
Rust explained using easy English
Rust 性能优化
zero2prod by Luca Palmieri
Comprehensive Rust This is a three day Rust course developed by the Android team.
Rust 面试
Rust 面试
Rust 其他
Rust 阅读清单
Rust 每日新闻
A bunch of links to blog posts, articles, videos, etc for learning Rust

博客和专栏

地址 (排名不分先后)
Rust 源码分析 @ 知乎专栏
Rust编程 @ 知乎专栏
夜雨秋灯录【使用 Rust 写 Parser】 @ 知乎专栏

Rust 视频

课程名称 简单介绍
Ashley Williams - intermezzOS: a teaching operating system
Felix Klock - Subtyping in Rust and Clarke's Third Law
RustConf 2020 Summary

Rust 播客

名称 简单介绍
Rusty Spike Podcast - News on all things Rust Short, weekly episodes packed with information.

Rust 博客

名称 简单介绍
A learning journal Zero To Production 系列教程
24 days of Rust

Rust 开发工具

1. Vim

MacVim + vim-rust

2. 文本编辑器 + 插件

Visual Studio CodeSublime Text 3Atom

VSCode 插件列表(欢迎大家补充):

插件名称 插件描述
Rust(rls) Rust 语言插件
GitLens 非常方便的查看文件代码的 commit 信息(提交时间,提交人等)。
Code Runner 针对非常多的语言而快速方便执行的小插件。
filesize 在 VSCode 底部工具栏,非常方便的显示文件大小。
Terminal 命令行工具插件。
Vim Vim 插件
VSCode Great Icons VSCode 美化不同的文件。
WakaTime 统计项目代码的时间。
BetterComments 代码注释

3. IDE

  • IntelliJ idea + Rust Plugin

Rust 社区

Rust 语言社区(排名不分先后) 特色
https://rust.cc/ Rust 每日新闻

微信公众号

微信公众号 (排名不分先后) 公众号 ID 二维码

Rust 夜读的日常技术讨论总结


Contributors

Thanks goes to these wonderful people (emoji key):


maiyang

💻 📝

This project follows the all-contributors specification. Contributions of any kind welcome!

learning-rust's People

Contributors

liyiheng avatar yangwenmai avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

learning-rust's Issues

Weekly Digest (19 May, 2019 - 26 May, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 8 stagazers.
tx991020
wotanjie
hellozepp
Easycker
nanpi
Rivsen
JaHIY
pdgz
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Q5: how to fix warning: unused variable?

当我们在什么 let remainder 但是又没有使用它时,编译器会直接给出警告。

warning: unused variable: `remainder`

运动 cargo run,直接给出帮助提示:

   |         ^^^^^^^^^ help: consider prefixing with an underscore: `_remainder`

T1: In rust must end with a semicolon?

在 Rust 中必须以分号结束?

fn main() {
    let f = false;
}

fn main() {
    let f = false
    let f: bool = true;
}

但是,如果你的语句是函数体的最后一行,可以省略分号。

fn main() {
    let f = false;
    let f: bool = true;
    println!("f is: {}, f2 is: {}", f, f2)
}

fn main() {
    let f = false;
    let f: bool = true;
    t()
}

fn t() {
    let f = false;
    let f: bool = true
    println!("f is: {}, f2 is: {}", f, f2)
}

表达式的结尾没有分号。如果在表达式的结尾加上分号,它就变成了语句,而语句不会返回值。

Q4: VSCode can't jump to defined function or struct?

解决办法

  1. 首先你得安装最新的 nightly 版本;

查看可用的最新的 nightly 版本:https://rust-lang.github.io/rustup-components-history/index.html

  1. VSCode 安装 RLS 服务;
  2. 命令行安装:
$ rustup component add rust-src --toolchain nightly-2019-04-21-x86_64-apple-darwin
$ rustup component add rust-analysis --toolchain nightly-2019-04-21-x86_64-apple-darwin
$ rustup component add rls --toolchain nightly-2019-04-21-x86_64-apple-darwin
$ rustup component add rustfmt --toolchain nightly-2019-04-21-x86_64-apple-darwin

我安装好之后,但是我的项目 guessing_game 中的 rand 相关库还是无法点击跳转呢?

原因是因为我的 toml 里面的 rand 版本设置为 0.3.23,只需要将 toml 里面的 rand 依赖版本改成0.4.0 就可以点击跳转了。

Q7: return not use ;

函数返回结果 Result 不能用

否则报错:

error[E0308]: mismatched types
  --> src/main.rs:94:27
   |
94 | fn run(config: Config) -> Result<(), Box<dyn Error>> {
   |    ---                    ^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found ()

从提示应该很明显了,但是我看这个提示一直想了很久/尝试了很多次,都没有改正确,我还怀疑是中文文档的问题。

去查英文 tutorial 对应这个例子,结果突然看到了 Ok(()) 是没有 ;,我才记起来。

在实践中,Rust 语法期望语句后面跟其他语句。这意味着用分号来分隔各个表达式。
这意味着 Rust 看起来很像大部分其他使用分号作为语句结尾的语言,并且你会看到分号出现在几乎每一行 Rust 代码。

那么我们说“几乎”的例外是什么呢?比如:

fn add_one(x: i32) -> i32 {
    x + 1;
}

我们的函数声称它返回一个 i32,不过带有一个分号的话,它将返回一个 ()。Rust 意识到这可能不是我们想要的,并在我们看到的错误中建议我们去掉分号:

Q9: error: no matching package named `sonr-extras` found

直接根据 cargo build 编译时的报错进行修复。

error: no matching package named `sonr-extras` found
location searched: https://github.com/hagsteel/sonr-extras
perhaps you meant: sonr_extras

原因是因为我自己写 dep 的时候,把 package sonr_extras 写成 sonr-extras 了。

Weekly Digest (13 October, 2019 - 20 October, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 6 stagazers.
GalaxyForce
xBINj
alvinfunborn
BigMurry
atbj505
jiecolo
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (22 December, 2019 - 29 December, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 5 stagazers.
emacsvi
tzh921129
yangchenglong11
yp2800
zagnix
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (29 September, 2019 - 6 October, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there was 1 stargazer.
Jessun1990
You are the star! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (2 June, 2019 - 9 June, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 5 stagazers.
xjtufjj
yaohcn
mytxd
gapry
arden
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Q6: cargo build error: index out of bounds when use a[10], but success when use a[index]

思考?

// 可以正确编译: cargo build
    let index = 10;
    let element = a[index];
    println!("The value of element is: {}", element);
    // 编译报错:cargo build
    println!("a[0] is: {}, a[6] is: {}", a[0], a[6]);// error: index out of bounds: the len is 5 but the index is 6
    let element = a[10];
    println!("The value of element is: {}", element);

为什么声明了一个变量值,然后通过这个变量值去取超过数组的索引时,不会报错。而直接使用常量值或明确的值时,会编译报错?

常量值的类型必须是 usize,否则报错: | ^^^^^^^^ slice indices are of typeusizeor ranges ofusize``

这个应该是跟编译器有关。

Weekly Digest (29 April, 2019 - 6 May, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


PULL REQUESTS

Last weeks (2019-04-29 10:40:12 +0000 UTC~2019-05-06 10:40:12 +0000 UTC), no pull requests were created, updated or merged.


COMMITS

Last weeks (2019-04-29 10:40:12 +0000 UTC~2019-05-06 10:40:12 +0000 UTC) there were/was 6 commits.
🛠️ chore(gitignore): ignore **/target by yangwenmai
🛠️ feat(cratesio): practives in cratesio by yangwenmai
🛠️ feat(search): config case sensitive by yangwenmai
🛠️ feat(search): change pub fn search to fn search by yangwenmai
🛠️ feat(search): impl search by tdd by yangwenmai
🛠️ feat(minigrep): impl minigrep by step by yangwenmai


RELEASES

Last weeks (2019-04-29 10:40:12 +0000 UTC~2019-05-06 10:40:12 +0000 UTC), no releases.


CONTRIBUTORS

Last weeks (2019-04-29 10:40:12 +0000 UTC~2019-05-06 10:40:12 +0000 UTC) there were/was 6 contributors.
👤 yangwenmai [6 commits]


Q1: error-component-rls-is-unavailable-for-download-nightly

VSCode 在打开 rs 文件后提示安装 rust-analysis 等,但是报错了

error: toolchain 'nightly-x86_64-apple-darwin' does not contain component 'rls' for target 'x86_64-apple-darwin'

解决办法:

https://github.com/rust-lang/rls#error-component-rls-is-unavailable-for-download-nightly

最终解决办法:rust-lang/rls#641 (comment)


For those who made it here looking for a workaround, the most recent toolchain I found which still has rls-preview is nightly-2019-04-19.

$ rustup toolchain install nightly-2019-04-21-x86_64-apple-darwin
$ rustup component add rls-preview --toolchain nightly-2019-04-21-x86_64-apple-darwin

Then in your VSCode user settings:

  "rust-client.channel": "nightly-2019-04-21-x86_64-apple-darwin"

Weekly Digest (26 May, 2019 - 2 June, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 2 stagazers.
xxxxzb
bingxueyuan
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (12 May, 2019 - 19 May, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week 1 issue was created.
It is closed now.

CLOSED ISSUES

❤️ #17 Weekly Digest (6 May, 2019 - 13 May, 2019), by yangwenmai


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there was 1 commit.
🛠️ docs(tutorial): single thread webserver by yangwenmai


CONTRIBUTORS

Last week there was 1 contributor.
👤 yangwenmai


STARGAZERS

Last week there was 1 stargazer.
xzs1994
You are the star! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (9 February, 2020 - 16 February, 2020)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 4 stagazers.
ST4RF4LL
wanken
byrybye
xyok
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (6 May, 2019 - 13 May, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


PULL REQUESTS

Last weeks (2019-05-06 10:40:19 +0000 UTC~2019-05-13 10:40:19 +0000 UTC), no pull requests were created, updated or merged.


COMMITS

Last weeks (2019-05-06 10:40:19 +0000 UTC~2019-05-13 10:40:19 +0000 UTC) there were/was 2 commits.
🛠️ feat(practices/gitignore): prictice the gitignore by yangwenmai
🛠️ feat(practices/chat): my practives for chat demo by yangwenmai


RELEASES

Last weeks (2019-05-06 10:40:19 +0000 UTC~2019-05-13 10:40:19 +0000 UTC), no releases.


CONTRIBUTORS

Last weeks (2019-05-06 10:40:19 +0000 UTC~2019-05-13 10:40:19 +0000 UTC) there were/was 2 contributors.
👤 yangwenmai [2 commits]


Weekly Digest (9 June, 2019 - 16 June, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week 2 issues were created.
Of these, 1 issues have been closed and 1 issues are still open.

OPEN ISSUES

💚 #23 Rust 和 Go 在图像处理上的性能之争, by yangwenmai

CLOSED ISSUES

❤️ #24 Update README.md, by XanthusL

LIKED ISSUE

👍 #23 Rust 和 Go 在图像处理上的性能之争, by yangwenmai
It received 👍 x4, 😄 x0, 🎉 x0 and ❤️ x0.

NOISY ISSUE

🔈 #23 Rust 和 Go 在图像处理上的性能之争, by yangwenmai
It received 1 comments.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there was 1 commit.
🛠️ Update README.md by XanthusL


CONTRIBUTORS

Last week there was 1 contributor.
👤 XanthusL


STARGAZERS

Last week there were 8 stagazers.
koqizhao
xieren58
cossonleo
baurine
zhangsoledad
Dengjianping
zsxh
readlnh
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (6 October, 2019 - 13 October, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 2 stagazers.
Rand01ph
LightStrawberry
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (2 February, 2020 - 9 February, 2020)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 4 stagazers.
BourneXu
syzby
linuer
whyisyoung
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Rust 和 Go 在图像处理上的简单对比

背景

大家都说 Rust 比较擅长系统底层,我猜想图像处理还是很底层的。

至少比较好用的都是 C 语言实现的。

imagemagick

libpng ? 也是 C 实现的。

那我们是不是可以来测试一下 Rust 和 Go 在图像处理上的表现呢?首先从 decode 开始。

Rust decode 一个图片文件

for _ in 0..10 {
    let timer = Instant::now();
    let tiny = image::open("examples/scaleup/out0.png").unwrap();
    println!("cost: {}", Elapsed::from(&timer));
}

耗时:

Decode in ~1.73 s

Rust 指定 Release 模式下运行 Decode 耗时 :

Decode in ~21 ms

image

还可以指定 opt-level3

Go decode 一个图片文件

startTime := time.Now()
data, err := ioutil.ReadFile("out0.png")
if err != nil {
 panic(err)
}
rd := bytes.NewReader(data)
image.Decode(rd)
fmt.Println("cost:", time.Now().Sub(startTime))

耗时:695.732µs

当时我就震惊了!!!

注意看上面的代码 image.Decode(rd) 这里有 error 返回,但是这里测试代码没有捕获。

其实它会报错:

panic: image: unknown format

代码修改为:

for i := 0;i < 10; i++ {
   startTime := time.Now()
   
   data, err := ioutil.ReadFile("rust.png")
   if err != nil {
      panic(err)
   }
   rd := bytes.NewReader(data)
   _,_,err = image.Decode(rd)
   if err != nil {
      panic(err)
   }
   
   fmt.Println("耗时:", time.Now().Sub(startTime))
}

使用 png 解析就正常了:

for i := 0;i < 10; i++ {
   startTime := time.Now()
   
   data, err := ioutil.ReadFile("rust.png")
   if err != nil {
      panic(err)
   }
   rd := bytes.NewReader(data)
   _, err = png.Decode(rd)
   if err != nil {
      panic(err)
   }
   
   fmt.Println("耗时:", time.Now().Sub(startTime))
}

执行耗时:
耗时: ~15.914074ms

Rust 和 Go 在对 png 图片进行 decode 时,两者的耗时差别并不大。

当我们将图片更换为 jpeg 后,他们的对比如下:

Rust(RELEASE模式下):

Decode in 3 ms

Go:

耗时: ~5.472894ms

对于 jpeg 的图片,Rust decode 要稍稍优于 Go 的 jpeg decode。


分析讨论过程

通过看 image 的源码发现 png 这个库 next frame 这个方法比较慢。
go版本一次性读整个图,png要一行一行的读,且每行都要一次内存拷贝
为了更高的抽象层级,有非常多细碎的内存拷贝
找到原因了:每行会创建一个Vec,一次Vec创建的时间在几十微秒左右,一个几百行的图片,主要会花在内存分配上

(准确说,单纯创建Vec不会发生堆内存分配,等价于一个栈上变量,代价可以忽略,但随后会对其写入,此时就会导致堆内存分配)

其实怎么存都有问题,抛开内存分配的问题,flatten到一维,行序,列序在处理的时候都对cache不友好

分析2:



主要不是内存分配的问题,其实在初始化的时候已经通过宏得到了图片大小,一次性分配好了。
主要是内存copy的问题,那里还注释了 TODO 待优化。

内存copy,还有下面那一行into转换,内存会重新分配吧,作者打算留给有缘人优化了。

Rust不保证代码的性能。

初学者用rust比较难写出高性能的程序吧,但是用go可以好一点。
应该是 初学者用rust比较难写出程序

写不好rust是我不行,不是rust不行。
很多人误以为,用rust写了代码就性能好了

其实我的印象里,内存拷贝的成本应该比内存分配低?

不过至少可以确定,image 这个库的速度确实是慢😂

我还测试了一下 jpeg 的解码,发现速度也一样糟糕

没法复用,他api设计的时候就断了复用的念头了

关键是后面解码的时候remalloc
读Row是个公开api,返回的是字节序列引用

作者还是有考虑的,可能处理时候有点问题,还没细看


Rust 还是一个新手,所以源代码和实现逻辑还得仔细研究研究再来理解大家的讨论了。

其他

环境:

MacBookPro 2017
3.1 GHz Intel Core i7
16 GB 2133 MHz LPDDR3

rustc 1.36.0-nightly (33fe1131c 2019-04-20)
cargo 1.36.0-nightly (b6581d383 2019-04-16)
Go 1.12.4

Rust 画一个○

使用 image-rs/imageproc 在一个 1000x1000 的画板上画一个 500x500 的圆:

//! An example using the drawing functions. Writes to the user-provided target file.

use std::env;
use std::path::Path;
use std::fmt;
use std::time::{Duration, Instant};
use image::{Rgb, RgbImage};
use imageproc::rect::Rect;
use imageproc::drawing::{
    draw_cross_mut,
    draw_line_segment_mut,
    draw_hollow_rect_mut,
    draw_filled_rect_mut,
    draw_hollow_circle_mut,
    draw_filled_circle_mut
};
struct Elapsed(Duration);
impl Elapsed {
    fn from(start: &Instant) -> Self {
        Elapsed(start.elapsed())
    }
}

impl fmt::Display for Elapsed {
    fn fmt(&self, out: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match (self.0.as_secs(), self.0.subsec_nanos()) {
            (0, n) if n < 1000 => write!(out, "{} ns", n),
            (0, n) if n < 1000_000 => write!(out, "{} µs", n / 1000),
            (0, n) => write!(out, "{} ms", n / 1000_000),
            (s, n) if s < 10 => write!(out, "{}.{:02} s", s, n / 10_000_000),
            (s, _) => write!(out, "{} s", s),
        }
    }
}

fn main() {
    let arg = if env::args().count() == 2 {
            env::args().nth(1).unwrap()
        } else {
            panic!("Please enter a target file path")
        };
    let timer = Instant::now();
    let path = Path::new(&arg);
    let white = Rgb([255u8, 255u8, 255u8]);

    let mut image = RgbImage::new(1000, 1000);
    // Draw a filled circle within bounds
    draw_filled_circle_mut(&mut image, (500, 500), 400, white);
    image.save(path).unwrap();
    println!("draw in {}", Elapsed::from(&timer));
}

Debug:
Output: draw in 1.22s

Release:
Output:draw in 20ms

image

注意:此样例代码,必须在 image-rs/imageproc/examples/drawing.rs 中运行。单独运行会报错:

error[E0277]: the trait bound `image::buffer::ImageBuffer<image::color::Rgb<u8>, std::vec::Vec<u8>>: image::image::GenericImage` is not satisfied
  --> src/main.rs:48:5
   |
48 |     draw_filled_circle_mut(&mut image, (500, 500), 400, white);
   |     ^^^^^^^^^^^^^^^^^^^^^^ the trait `image::image::GenericImage` is not implemented for `image::buffer::ImageBuffer<image::color::Rgb<u8>, std::vec::Vec<u8>>`
   |
   = note: required by `imageproc::drawing::conics::draw_filled_circle_mut`

Go 画一个○

package main

import (
	"bytes"
	"fmt"
	"github.com/fogleman/gg"
	"image"
	"io"
	"io/ioutil"
	"time"
)

func main() {
	startTime := time.Now()
	dc := gg.NewContext(1000, 1000)
	dc.DrawCircle(500, 500, 400)
	dc.SetRGB(0, 0, 0)
	dc.Fill()

	dc.SavePNG("out.png")

	// 99.617772ms ~ 108.1321ms
	fmt.Println("耗时:", time.Now().Sub(startTime))
}

耗时:99ms ~ 108ms 左右。

image

简单对比 Rust 比 Go 快 5 倍。(这个还是非常值得期待的,但是两者图像不太一样,所以还需要修补修补)
以上代码:https://github.com/developer-learning/learning-rust/tree/master/practices/image

翻转我的头像文件(不生成文件)

使用 github.com/disintegration/imaging 库:

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/disintegration/imaging"
)

func main() {
	for i := 0; i < 10; i++ {
		startTime := time.Now()
		img, err := imaging.Open("avatar-origin.jpg")
		if err != nil {
			log.Fatalln(err)
			return
		}
		imaging.FlipH(img)
		fmt.Println("cost:", time.Now().Sub(startTime))
	}
}

使用 Rust 的 image crate 源代码:

extern crate image;

use image::{FilterType, PNG};
use std::fmt;
use std::fs::File;
use std::time::{Duration, Instant};

struct Elapsed(Duration);

impl Elapsed {
    fn from(start: &Instant) -> Self {
        Elapsed(start.elapsed())
    }
}

impl fmt::Display for Elapsed {
    fn fmt(&self, out: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match (self.0.as_secs(), self.0.subsec_nanos()) {
            (0, n) if n < 1000 => write!(out, "{} ns", n),
            (0, n) if n < 1000_000 => write!(out, "{} µs", n / 1000),
            (0, n) => write!(out, "{} ms", n / 1000_000),
            (s, n) if s < 10 => write!(out, "{}.{:02} s", s, n / 10_000_000),
            (s, _) => write!(out, "{} s", s),
        }
    }
}

fn main() {
    for _ in 0..10 {
        let timer = Instant::now();
        let tiny = image::open("examples/scaleup/avatar-origin.jpg").unwrap();
        tiny.fliph();
        println!("Decode in {}", Elapsed::from(&timer));
    }
}

执行10次,耗时:

非 release 模式下执行:

Cost in 550 ms

Rust decode && flip h 比 Go github.com/disintegration/imaging decode && flip h 要快 8 ms。

Go :

cost: 26.731724ms

Rust release 模式下:

Cost 17 ms

Go decode && flip h && save 比 Rust decode && flip h && save 要快 8 ms。

Go decode && flip h && save cost:

cost: 75.040754ms

Rust decode && flip h && save cost:

Cost in 81 ms

去掉 flip ,纯 image decode 然后再 save,则 Rust 比 Go 慢 10ms:

Go decode && save:

cost: 68.575711ms

Rust decode && save:

Cost in 77 ms

一探究竟

上面的代码中 Go decode && flip h && save 比 Rust 快 8-10 ms,我们也已经知道差距是在 save。
所以我们研究一下 Go 和 Rust 的 save 部分代码。

Go 代码:

var defaultEncodeConfig = encodeConfig{
	jpegQuality:         95,
	gifNumColors:        256,
	gifQuantizer:        nil,
	gifDrawer:           nil,
	pngCompressionLevel: png.DefaultCompression,
}

很明显 Go save 的时间比较小是因为 jpegQuality 默认是 95 ,所以指定 jpegQuality 为 100: err = imaging.Save(img, "newavatar-origin-flip-h.jpg", imaging.JPEGQuality(100)) 执行:

cost: 89.767576ms

Go 整体执行时间比 Rust 多 3-5ms。

缩放

Go:

img = imaging.Fit(img, 200, 200, imaging.Lanczos)

Rust:

let mut d = tiny.resize(200, 200, FilterType::Lanczos3);

旋转

Go:

img = imaging.Rotate(img, -90, color.RGBA{0, 0, 0, 0})

Rust:

let mut d = tiny.rotate90();

参考资料

  1. https://github.com/image-rs/image
  2. https://github.com/golang/go#image
  3. image-rs/image-png#61
  4. Rust 和 Go 在图像处理上的性能之争
  5. Drawing a circle, but cost over 1 second, it's normal? #324

引用 wish:

语言层面 micro benchmark 还是挺多的,这些衡量语言本身性能的好坏应该足够了。至于库的话,生态也是语言的一部分,是工程中需要参考的因素。比如我觉得衡量 grpc go 性能和 grpc c core 性能差距得出语言性能差距,本身意义不大,但如果要用 grpc,那么是个很好的参考了。

我个人非常认同,语言好坏并不是一概而论的,有时候你得考虑更多方面,比方说:工程化、生态等。

Weekly Digest (16 February, 2020 - 23 February, 2020)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there were 8 stagazers.
kasheemlew
ericmm
chrisxiao
henrylee2cn
ccl0326
jmjoy
luxious
madfrog2047
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (16 June, 2019 - 23 June, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, 1 pull request was created, updated or merged.

MERGED PULL REQUEST

Last week, 1 pull request was merged.
💜 #24 Update README.md, by XanthusL


COMMITS

Last week there were 2 commits.
🛠️ docs(post): add rust vs go decode image by yangwenmai
🛠️ Merge pull request #24 from XanthusL/patch-1 Update README.md by yangwenmai


CONTRIBUTORS

Last week there was 1 contributor.
👤 yangwenmai


STARGAZERS

Last week there were 32 stagazers.
wj-zhu
brileyhe
gcf0082
Baoyx007
efeng1st
vsmawoex
mayneyao
Hucy
smolkov
MistShi
wendzhue
wangpengwen
sunclx
L1MeN9Yu
langzime
chenjianxin
promer94
Observer42
thinkhero
finian
qboster
leaxoy
n4to4
zhangji0629
Sanhajio
tracyStar
dimlev
CrystalBlack
itfanr
ahjdzx
guanguans
barryz
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (6 May, 2019 - 13 May, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week 5 issues were created.
Of these, 0 issues have been closed and 5 issues are still open.

OPEN ISSUES

💚 #16 【项目实践】use git-ignore to add ignore file for your project, by yangwenmai
💚 #15 Q10: cargo install unsupported and repleaced by cargo install --path ., by yangwenmai
💚 #14 Q9: error: no matching package named sonr-extras found, by yangwenmai
💚 #13 【项目实践】use sonr and sonr_extras for chat, by yangwenmai
💚 #12 Weekly Digest (29 April, 2019 - 6 May, 2019), by yangwenmai


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were 2 commits.
🛠️ feat(practices/gitignore): prictice the gitignore by yangwenmai
🛠️ feat(practices/chat): my practives for chat demo by yangwenmai


CONTRIBUTORS

Last week there was 1 contributor.
👤 yangwenmai


STARGAZERS

Last week there were 2 stagazers.
cxapython
SupBK
You all are the stars! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Weekly Digest (22 September, 2019 - 29 September, 2019)

Here's the Weekly Digest for developer-learning/learning-rust:


ISSUES

Last week, no issues were created.


PULL REQUESTS

Last week, no pull requests were created, updated or merged.


COMMITS

Last week there were no commits.


CONTRIBUTORS

Last week there were no contributors.


STARGAZERS

Last week there was 1 stargazer.
orator1
You are the star! 🌟


RELEASES

Last week there were no releases.


That's all for last week, please 👀 Watch and Star the repository developer-learning/learning-rust to receive next weekly updates. 😃

You can also view all Weekly Digests by clicking here.

Your Weekly Digest bot. 📆

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.