DataCamp课程 <高效率代码> Chapter1. Benchmarking

高效率代码课程目录

Chapter1. Benchmarking
Chapter2. R语言高效化基础
Chapter3. 查看Code内部
Chapter4. 多线程计算

查看R版本

version就可以,但是注意version不是一个函数。

# Print the R version details using version
version
               _                           
platform       x86_64-pc-linux-gnu         
arch           x86_64                      
os             linux-gnu                   
system         x86_64, linux-gnu           
status                                     
major          3                           
minor          4.4                         
year           2018                        
month          03                          
day            15                          
svn rev        74408                       
language       R                           
version.string R version 3.4.4 (2018-03-15)
nickname       Someone to Lean On 

这个课程里用到的镜像程序是3.4.4,有点旧。最新的R是4.0.0+

读取csvrds

在读取数据的时候我们经常会用到cvs格式。但是在遭遇大数据的时候读取cvs会非常缓慢。还有一种格式是rds。读取rds会比较快。

# How long does it take to read movies from CSV?
system.time(read.csv("movies.csv"))
   user  system elapsed 
  0.335   0.012   0.348 
# How long does it take to read movies from RDS?
system.time(readRDS("movies.rds"))
   user  system elapsed 
  0.043   0.004   0.047 

=<-是不是有区别

答案是有区别。优先级别不一样,<-优先于=
试一下下面的代码就知道了。

x <- y = 10
Error: object 'x' not found
>
x = y <- 10

比较程序运行时间

system.time()可以用来计算程序运行时间,但是在比较多个程序的时候就有点力不从心了。可以使用microbenchmark包里的microbenchmark函数来解决这个问题。
比方说我们可以比较read.csv("movies.csv"), readRDS("movies.rds")
(各自运行了10次)。

# Load the microbenchmark package
library(microbenchmark)
# Compare the two functions
compare <- microbenchmark(read.csv("movies.csv"), 
                          readRDS("movies.rds"), 
                          times = 10)
# Print compare
compare
Unit: milliseconds
                   expr       min       lq      mean    median        uq
 read.csv("movies.csv") 314.94812 385.8338 422.32921 437.90361 451.31641
  readRDS("movies.rds")  40.43044  44.9342  52.54306  54.03195  59.89902
       max neval
 503.41147    10
  62.16677    10

查看设备配置

benchmarkme可以简单迅速的查看当前设备的内存,CPU等配置。

# Load the benchmarkme package
library(benchmarkme)
# Assign the variable ram to the amount of RAM on this machine
ram <- get_ram()
ram
33.7 GB
# Assign the variable cpu to the cpu specs
cpu <- get_cpu()
cpu
$vendor_id
[1] "GenuineIntel"

$model_name
[1] "Intel(R) Xeon(R) CPU"

$no_of_cores
[1] 8

查看设备速度排名

benchmarkme还可以同过这个包的算法写出一个指定大小的文件,然后看所需要时间的排名。就当玩玩就好了。

# Load the package
library("benchmarkme")

# Run the io benchmark
# 文件大小:5M
res <- benchmark_io(runs = 1, size = 5)

# Plot the results
plot(res)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容