Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

r - Strange behaviour when printing execution time using Sys.time()

I have the sample code below:

f <- function(x) {
  v = 0
  start = Sys.time()
  for (i in 1:x) {
    v = v + 1
  }
  end = Sys.time()
  print(end-start)
  print(paste0("f() took: ", end-start))
}

f(10)

The 2 outputs are:

  1. Time difference of 5.960464e-06 secs
  2. "f() took: 5.96046447753906e-06"

My question is why when used with paste0 the output is different.

Edit:

If one wish to get the units of time do the following:

print(paste0("f() took: ", end-start, " ", units(end-start)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have a look at ?print.difftime:

The print() method calls these “time differences”.

It's an in-built method for print that displays differences in dates in this format.

class(Sys.Date()-Sys.Date()+1)
[1] "difftime"

class(paste(Sys.Date()-Sys.Date()+1))
[1] "character"

paste0("f() took: ", end-start) becomes a character class and so print will handle it differently


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...