Skip to content
This repository was archived by the owner on Jul 9, 2024. It is now read-only.

R语言28-R语法: 程序优化 #15

Open
SiYangming opened this issue May 28, 2022 · 0 comments
Open

R语言28-R语法: 程序优化 #15

SiYangming opened this issue May 28, 2022 · 0 comments

Comments

@SiYangming
Copy link
Owner

https://siyangming.github.io/blogs/R_28-R_program_design/

编写R代码

使用文本文件或编辑器 Always use text files / text editor
适当的缩进
限制代码的宽度
限制自定义函数的长度

缩进

缩进提高代码的可读性
限制代码的长度,避免过多的嵌套和太长的函数
最少缩进4个空格,8个更完美

程序设计

检查程序代码不同部分的执行时间对于代码优化很有用。
通常代码运行一次会表现良好,但如果你将其放如1000次循环中,运行效率是否受到影响,这时分析运行时间很有用。

优化代码

影响代码执行速度的最大因素是代码花费最多时间的部分
不通过程序执行时间分析很难完成

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil(过早最优化是万恶的根源)

–Donald Knuth

优化的一般目标

先设计后优化
过早优化是万恶的根源
操作(收集数据),不要猜测
科学家的基本素养

使用 system.time()

接收任意R表达是作为输入,返回运行该表达式所需要的时间
计算执行表达所需要的时间(秒)

  如果有错误,返回报错前的时间

返回 proc_time 类的对象

  user time: CPU时间
  elapsed time: 总流逝时间

对于直接的计算任务,user time和elapsed time很接近
如果CPU花费大量的等待时间,elapsed time会比user time大很多
如果机器拥有多线程elapsted time会比user time小很多

  多线程BLAS库 (vecLib/Accelerate, ATLAS, ACML, MKL)
  多线程包parallel 

system.time(readLines(

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant