<p>Thanks to Jonas Londelov, I've been able to rewrite the script for measuring multiple keys until esc is pressed and writing the key duration, the key and the info into an excel sheet. It might not be very good written I a python beginner, but it is useful. Perhaps someone else will need it.</p>

<pre><code>from __future__ import division
from psychopy import visual, event, core, data, iohub
from psychopy.iohub import launchHubServer 
io = iohub.launchHubServer
import csv
io = launchHubServer()
keyboard = io.devices.keyboard  # handy name
count = 0
keyinfo = ""
duration = 0
key = ""
time = core.getTime()
date = data.getDateStr(format='%Y_%b_%d_%H%M')#(format="%Y_%m_%d %H:%M (Year_Month_Day Hour:Min)")

io.clearEvents('all')
win = visual.Window([400, 400])
msg = visual.TextStim(win, text='press a key\n &lt; esc &gt; to quit')
msg.draw()
win.flip()

datafile = open("touch duration.csv", "wb") #$not overwriting but longer
writer = csv.writer(datafile, delimiter=";")
# create output file header
writer.writerow([
    date,
    "round", 
    "keyinfo", 
    "duration",
    "key",
    ])

while key not in ['escape', 'esc']:
    key_info = keyboard.waitForReleases()[0]  # Just grab first release, even if there are multiple
    count += 1
    key = key_info.key
    keyinfo = key_info
    duration = key_info.duration
    key = key_info.key
    print 'round number:' , count
    print key_info
    print 'Press time was', key_info.duration
    print 'key', key_info.key
    writer.writerow([
    "",
    count, 
    keyinfo, 
    duration,
    key,
    ])
</code></pre>

CC BY-SA 3.0
2017-06-12T12:10:44.963Z
You can simplify this. First, just one import line: `from psychopy import visual, event, core, data, iohub` and then do `io = iohub.launchHubServer`. Second, no need to call `win.close`, `data.file.close` and `core.quit`. This will happen automatically when the script closes. Third, you re-define some variables, e.g. `time` and `date`,`key` etc. Just delete the first one since it is "overwritten" anway.
Jonas Lindeløv
CC BY-SA 3.0
2017-06-14T23:56:37.580Z
Thank you I've edited the answer to inlcude your corrections.
Nathalie
CC BY-SA 3.0
2017-06-11T22:48:33.200Z
2017-06-14T23:55:47.757Z
2017-06-14T23:55:47.757Z
Nathalie
<p>If accuracy is important, perhaps try the GPL'd TScope, which is a C library; there's a <a href="https://www.ncbi.nlm.nih.gov/pubmed/16956104" rel="nofollow noreferrer">paper about it (alas for old version)</a> with a moderate number of citations. It's also maintained (<a href="http://expsy.ugent.be/tscope5/index.html" rel="nofollow noreferrer">current version is 5</a>) and they have <a href="http://expsy.ugent.be/tscope5/timer06_8c-example.html" rel="nofollow noreferrer">an example measuring keypress duration</a>. It's easy enough to use as they pack everything you'd need on Windows, including a customized version of Notepad++ with shortcuts for compiling and running a program.  The odd thing is that the examples from the website seem missing from the 145Mb package, but they work compiled with it.</p>

<p>I don't have any high-speed camera to test the accuracy, but from a quick test on myself, I didn't see any large deviations. Using a long-stroke PS/2 keyboard I get around 95ms press time (that seem on par with the <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3256245/figure/F4/" rel="nofollow noreferrer">paper you mentioned</a>). With a short stroke USB keyboard , I get as low as 55ms, if I focus specifically on just making short strokes (and this does seem to come at the cost of reaction time, I need sorta "prepare myself" to make a really short stroke; in normal typing I'm still in the habit of pressing longer, even though this keyboard doesn't need it). Here's an example of the later:</p>

<p><a href="https://i.sstatic.net/n97Dm.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/n97Dm.png" alt="enter image description here"></a></p>

CC BY-SA 3.0
2017-12-28T05:18:19.747Z
2017-12-28T11:40:57.813Z
2017-12-28T11:40:57.813Z
got trolled too much this week


<p>Psychopy (<a href="http://psychopy.org" rel="nofollow noreferrer">http://psychopy.org</a>) can do this. It can do it in two ways.</p>

<ol>
<li><p>Using iohub. Iohub is a crazy powerful way to get any information about any kind of input to your system, from keyboard, mouse, eye-trackers, etc. You can see the documentation for keyboard <a href="http://www.psychopy.org/api/iohub/device/keyboard.html" rel="nofollow noreferrer">here</a>.</p>

<pre><code>from psychopy.iohub import launchHubServer
io = launchHubServer()
keyboard = io.devices.keyboard  # handy name

print 'start pressing a key now'
key_info = keyboard.waitForReleases()[0]  # Just grab first release, even if there are multiple
print 'Press time was', key_info.duration
print '... and BTW, all key event info was', key_info
</code></pre></li>
<li><p>Using pyglet: </p>

<pre><code>from psychopy import visual, event, core
win = visual.Window()  # Disadvantage: you need to have a window open to record it.
clock = core.Clock()

# Start listening
print 'start pressing a key now'
key, time = event.waitKeys(timeStamped=True)[0]
clock.reset()  # Key down time
while event.getKeys():
    pass
print 'key lasted', clock.getTime(), 'seconds'
</code></pre></li>
</ol>

<p>If measuring key strokes is the only thing you need, psychopy may be a bit heavy since it is meant for running full experiments, but it will do the job!</p>

CC BY-SA 3.0
2017-06-09T19:20:47.997Z
I was just starting to answer this question with reference to PsychoPy :) +1
AliceD
CC BY-SA 3.0
2017-06-09T19:51:24.890Z
Thank you! Tried the pyglet solution first, because opening a new window is even better for me. It works perfectly!
Nathalie
CC BY-SA 3.0
2017-06-10T00:51:31.293Z
while trying the first one an error occured about launch Hub server. After including `from psychopy.iohub import launchHubServer` it works great. Thanks.
Nathalie
CC BY-SA 3.0
2017-08-02T02:03:42.040Z
I was wondering is there a difference in accuracy between these two solutions? I've been searching for it but haven't found any data for windows.  Does anyone know something about this?
Nathalie
CC BY-SA 3.0
2017-06-09T19:19:20.323Z
2018-01-03T20:58:59.047Z
2018-01-03T20:58:59.047Z
Jonas Lindeløv
<p>I am searching for freeware to measure the duration of a keystroke or mouse-click, both would work. Does anyone have an idea?</p>

<p>Matlab toolboxes are, unfortunately, of no use to me.</p>

CC BY-SA 3.0
2017-06-09T18:48:00.303Z
A shame Matlab is of no use to you - The [**PTB-3 toolbox**](http://psychtoolbox.org/) contains functions specifically to record keystrokes, even allowing for quite accurate reaction time measurements on a Windows OS. There are other users on this site that may be of help though. Let's see what comes up!
AliceD
CC BY-SA 3.0
2017-06-09T18:51:33.520Z
thanks a lot! Its at least good to know that this would work, if no one else has an idea.
Nathalie
CC BY-SA 3.0
2017-06-19T20:39:53.660Z
What would this be used in studying psychophysics?
Ooker
CC BY-SA 3.0
2017-06-20T08:27:23.043Z
It can be used for things that have been worked on in this article "Typing keystroke duration changed after submaximal isometric finger exercises" or I've seen also writing speed for each character. I am using it for something different, my device codes stimuli as keyboard strokes, therefore I can distinguish different stimuli and measure the time of application.
Nathalie
CC BY-SA 3.0
2017-12-30T02:17:10.487Z
@Nathalie are your indices of interest the same as those used in studies of keystroke dynamics e.g. flight time, dwell time?
faustus
CC BY-SA 3.0
2017-12-30T19:20:45.580Z
@AliceD [PTB-3](http://psychtoolbox.org/requirements/) runs on Octave so is valid answer.
StrongBad
CC BY-SA 3.0
2017-12-30T19:24:22.717Z
@StrongBad - It does? Thanks for that! I might add my 2-cents worth then after all :D
AliceD
CC BY-SA 3.0
2017-12-30T19:26:00.983Z
@AliceD I will give you an upvote after you answer and clean up these comments ;)
StrongBad
<measurement><methodology><psychophysics>
Freeware for measuring keystroke duration
Nathalie
# Freeware for measuring keystroke duration

(Asked by: username_0 on 2017-06-09)

I am searching for freeware to measure the duration of a keystroke or mouse-click, both would work. Does anyone have an idea?

Matlab toolboxes are, unfortunately, of no use to me.

**Tags:** measurement, methodology, psychophysics

> **Comments:**
> **username_1**: A shame Matlab is of no use to you - The [**PTB-3 toolbox**](http://psychtoolbox.org/) contains functions specifically to record keystrokes, even allowing for quite accurate reaction time measurements on a Windows OS. There are other users on this site that may be of help though. Let's see what comes up!  
> **username_0**: thanks a lot! Its at least good to know that this would work, if no one else has an idea.  
> **username_2**: What would this be used in studying psychophysics?  
> **username_0**: It can be used for things that have been worked on in this article "Typing keystroke duration changed after submaximal isometric finger exercises" or I've seen also writing speed for each character. I am using it for something different, my device codes stimuli as keyboard strokes, therefore I can distinguish different stimuli and measure the time of application.  
> **username_3**: @username_0 are your indices of interest the same as those used in studies of keystroke dynamics e.g. flight time, dwell time?  
> **username_4**: @username_1 [PTB-3](http://psychtoolbox.org/requirements/) runs on Octave so is valid answer.  
> **username_1**: @username_4 - It does? Thanks for that! I might add my 2-cents worth then after all :D  
> **username_4**: @username_1 I will give you an upvote after you answer and clean up these comments ;)  

---

## 3 answers

### Answer by username_5 on 2017-06-09. Score: 6 | Accepted answer

Psychopy (http://psychopy.org) can do this. It can do it in two ways.

Using iohub. Iohub is a crazy powerful way to get any information about any kind of input to your system, from keyboard, mouse, eye-trackers, etc. You can see the documentation for keyboard here.
from psychopy.iohub import launchHubServer
io = launchHubServer()
keyboard = io.devices.keyboard  # handy name

print 'start pressing a key now'
key_info = keyboard.waitForReleases()[0]  # Just grab first release, even if there are multiple
print 'Press time was', key_info.duration
print '... and BTW, all key event info was', key_info

Using pyglet: 
from psychopy import visual, event, core
win = visual.Window()  # Disadvantage: you need to have a window open to record it.
clock = core.Clock()

# Start listening
print 'start pressing a key now'
key, time = event.waitKeys(timeStamped=True)[0]
clock.reset()  # Key down time
while event.getKeys():
    pass
print 'key lasted', clock.getTime(), 'seconds'


If measuring key strokes is the only thing you need, psychopy may be a bit heavy since it is meant for running full experiments, but it will do the job!

> **Comments:**
> **username_1**: I was just starting to answer this question with reference to PsychoPy :) +1  
> **username_0**: Thank you! Tried the pyglet solution first, because opening a new window is even better for me. It works perfectly!  
> **username_0**: while trying the first one an error occured about launch Hub server. After including `from psychopy.iohub import launchHubServer` it works great. Thanks.  
> **username_0**: I was wondering is there a difference in accuracy between these two solutions? I've been searching for it but haven't found any data for windows.  Does anyone know something about this?  

---

### Answer by username_0 on 2017-06-11. Score: 2

Thanks to Jonas Londelov, I've been able to rewrite the script for measuring multiple keys until esc is pressed and writing the key duration, the key and the info into an excel sheet. It might not be very good written I a python beginner, but it is useful. Perhaps someone else will need it.
from __future__ import division
from psychopy import visual, event, core, data, iohub
from psychopy.iohub import launchHubServer 
io = iohub.launchHubServer
import csv
io = launchHubServer()
keyboard = io.devices.keyboard  # handy name
count = 0
keyinfo = ""
duration = 0
key = ""
time = core.getTime()
date = data.getDateStr(format='%Y_%b_%d_%H%M')#(format="%Y_%m_%d %H:%M (Year_Month_Day Hour:Min)")

io.clearEvents('all')
win = visual.Window([400, 400])
msg = visual.TextStim(win, text='press a key\n < esc > to quit')
msg.draw()
win.flip()

datafile = open("touch duration.csv", "wb") #$not overwriting but longer
writer = csv.writer(datafile, delimiter=";")
# create output file header
writer.writerow([
    date,
    "round", 
    "keyinfo", 
    "duration",
    "key",
    ])

while key not in ['escape', 'esc']:
    key_info = keyboard.waitForReleases()[0]  # Just grab first release, even if there are multiple
    count += 1
    key = key_info.key
    keyinfo = key_info
    duration = key_info.duration
    key = key_info.key
    print 'round number:' , count
    print key_info
    print 'Press time was', key_info.duration
    print 'key', key_info.key
    writer.writerow([
    "",
    count, 
    keyinfo, 
    duration,
    key,
    ])

> **Comments:**
> **username_5**: You can simplify this. First, just one import line: `from psychopy import visual, event, core, data, iohub` and then do `io = iohub.launchHubServer`. Second, no need to call `win.close`, `data.file.close` and `core.quit`. This will happen automatically when the script closes. Third, you re-define some variables, e.g. `time` and `date`,`key` etc. Just delete the first one since it is "overwritten" anway.  
> **username_0**: Thank you I've edited the answer to inlcude your corrections.  

---

### Answer by username_6 on 2017-12-28. Score: 1

If accuracy is important, perhaps try the GPL'd TScope, which is a C library; there's a [paper about it (alas for old version)](https://www.ncbi.nlm.nih.gov/pubmed/16956104) with a moderate number of citations. It's also maintained ([current version is 5](http://expsy.ugent.be/tscope5/index.html)) and they have [an example measuring keypress duration](http://expsy.ugent.be/tscope5/timer06_8c-example.html). It's easy enough to use as they pack everything you'd need on Windows, including a customized version of Notepad++ with shortcuts for compiling and running a program. The odd thing is that the examples from the website seem missing from the 145Mb package, but they work compiled with it.

I don't have any high-speed camera to test the accuracy, but from a quick test on myself, I didn't see any large deviations. Using a long-stroke PS/2 keyboard I get around 95ms press time (that seem on par with the [paper you mentioned](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3256245/figure/F4/)). With a short stroke USB keyboard , I get as low as 55ms, if I focus specifically on just making short strokes (and this does seem to come at the cost of reaction time, I need sorta "prepare myself" to make a really short stroke; in normal typing I'm still in the habit of pressing longer, even though this keyboard doesn't need it). Here's an example of the later:

[![enter image description here](https://i.sstatic.net/n97Dm.png)](https://i.sstatic.net/n97Dm.png)


---

