Reputation: 31
I am trying to capture the timing in millisecond between the KeyDown
and KeyUp
, the elapsed time between those two events for each typed character, I used Stopwatch.GetTimestamp()
since I need to acquire a high-resolution time stamps, as shown in the coding below, and I wonder if this is the correct equation to get the time in millisecond:
int timeStampInMiliseconds = Convert.ToInt32(elapsedTicks * 1000000 / Stopwatch.Frequency);
for getting the time in millisecond.
Since the timing results does not show any consistency and could reach up to 5 seconds between those two events, which is not realistic!!
public partial class Form1 : Form
{
long timeStamp;
long initialTimeStamp;
public Form1()
{
InitializeComponent();
Stopwatch stopWatch = new Stopwatch();
// Uses the second Core or Processor for the Test
// Prevents "Normal" processes from interrupting Threads
// Prevents "Normal" Threads
initialize();
}
public void initialize()
{
//
}
public void textBox1_KeyDown(object sender, KeyEventArgs e)
{
initialTimeStamp = Stopwatch.GetTimestamp();
}
public void textBox1_KeyUp(object sender, KeyEventArgs e)
{
timeStamp = Stopwatch.GetTimestamp();
long elapsedTicks = timeStamp -initialTimeStamp;
int timeStampInMiliseconds = Convert.ToInt32(elapsedTicks * 1000000 / Stopwatch.Frequency);
}
}
Really appreciating your help.
Upvotes: 0
Views: 696
Reputation: 25351
You don't need to use the Stopwatch
. It is much easier to get a timestamp using:
long t = DateTime.Now.Ticks;
Try this:
public void textBox1_KeyDown(object sender, KeyEventArgs e)
{
initialTimeStamp = DateTime.Now.Ticks;
}
public void textBox1_KeyUp(object sender, KeyEventArgs e)
{
timeStamp = DateTime.Now.Ticks;
long elapsedTicks = timeStamp - initialTimeStamp;
long timeStampInNanoseconds = elapsedTicks * 100;
}
I did it in Nanoseconds for more accuracy, but you can convert to Milliseconds if you like:
long timeStampInMiliseconds = elapsedTicks / 10000;
Upvotes: 0
Reputation: 27861
A better way to do this is to use the StopWatch.ElapsedMilliseconds
property.
In the textBox1_KeyDown
event handler, simply restart the stop watch like this:
stopWatch.Restart();
And in the textBox1_KeyUp
event handler, read the ElapsedMilliseconds
property like this:
long timeStampInMiliseconds = stopWatch.ElapsedMilliseconds;
You also need to make the stopWatch
an instance variable like this:
public partial class Form1 : Form
{
long timeStamp;
long initialTimeStamp;
Stopwatch stopWatch;
public Form1()
{
InitializeComponent();
stopWatch = new Stopwatch();
....
}
....
}
Upvotes: 3