Time user input from first keystroke in R

自作多情 提交于 2019-12-10 17:49:59

问题


Looking to time how long it takes a user to type a message in R from the first keystroke.

I can use functions like readline() or scan() to get the user input, and I can use the system.time() to measure how long it takes for the code to be run:

> system.time(readline())
Test Message
   user  system elapsed 
   0.98    0.53   19.55

However, these give me the total elapsed time. If I wait wait 15 seconds before typing, this is reflected in the output of system.time(), and not just the time I spent to write the message. (E.g 19.55s = 15s + ~4.5s I used to type the message.)

Looking for this to happen in the console, but also willing to use a separate window if necessary.


回答1:


I recently solved this issue using a combination of two packages - tictoc and keypress.

From keypress you can use the keypress() function that waits for user input and then outputs the key that was pressed - keypress() only works in R on command line and it supports the majority of keys, but not all of them.

To time from a keypress you can write a simple if statement that calls the tic() function from tictoc.

Example

When I posted this question I was looking to time how long it would take someone to type the entire lowercase alphabet after hitting the 'a' key.

require(tictoc)
require(keypress)

for(i in 1:26){

  a=keypress()

  if(a==letters[1])  tic()
  if(a==letters[26]) toc()

  cat(paste(a))
}

abcdefghijklmnopqrstuvwxyz6.649 sec elapsed

This starts the stopwatch when 'a' is hit, and then stops it when the 'z' key is pressed.



来源:https://stackoverflow.com/questions/47514592/time-user-input-from-first-keystroke-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!