vb 如何精确到毫秒的时间差?
我操作两次然后要得到这两次操作的时间差
要求精确到毫秒
怎么做?
追问:这个我有试过非常的不准确
我操作两次然后要得到这两次操作的时间差
要求精确到毫秒
怎么做?
追问:这个我有试过非常的不准确
答案:试过NN次后,我“也”发现这种记录时间的精度为10.0144毫秒,
看来,这个问题是由CLR决定的,如果,只使用FCL的函数,看来没办法解决这一问题了!
看了 LoveCherry(论成败,人生豪迈;大不了,重头再来!^_^) ,给出的文章链接,
http://blog.joycode.com/lostinet/archive/2005/04/24/49590.aspx
受了些启发,对于文章中实现的那个A类,我没看太明白,但是,文章中用到了QueryPerformanceCounterp这个win API函数,楼主,可以导入用一下,我试过多次,在我的机子上,其精度为 210/1000 毫秒左右。
QueryPerformanceCounter这个函数的是一个计数器函数,以百万分之一秒为单位,来记算时间数。
//=============
using System.Runtime.InteropServices;
using System.Threading;
[DllImport("kernel32.dll")]
static extern bool QueryPerformanceCounter([In, Out] ref long lpPerformanceCount);
long t1 = 0;
long t2 = 0;
QueryPerformanceCounter(ref t1);
Thread.Sleep(1); //挂起一毫秒,作为演示
QueryPerformanceCounter(ref t2);
long sp = t2 - t1;//sp的单位为百万分之一秒
float f_time = (float)((decimal) sec / (decimal)10000); //得到0.0001毫秒的精度
f_time = float.Parse(string.Format("{0:F1}",f_time)); //f_time是经过四舍五入,得到的0.1毫秒的精度搞一个Timer控件就可以了,第一个操作使它的Enabled属性改为True,第二个操作再改为False,Timer的interval属性改为1,然后在代码区加入以下代码(这里我用两个按钮的Click事件来表示两个操作)
Dim a As Long
Private Sub Command1_Click()
Timer1.Enabled = True
End SubPrivate Sub Command2_Click()
Timer1.Enabled = True
MsgBox Str$(a)
a = 0
End SubPrivate Sub Form_Load()
Timer1.Enabled = False
a = 0
End SubPrivate Sub Timer1_Timer()
毫秒很容易,纳秒也可以,看看vb里有什么函数,不行,自己读硬件时钟发生器
a = a + 1
End Sub
Public Declare Function timeGetTime Lib "winmm.dll" Alias "timeGetTime" () As Long
操作之前取一个时间,操作之后取一个时间,两个相减就是毫秒级的计时可以用WINAPI函数GetTickCount,它的单位就是1mS。
Public Declare Function GetTickCount Lib "kernel32" Alias "GetTickCount" () As Long
Dim T1 as long, T2 as long
T1=GetTickCount()
。。。
T2=GetTickcount()
Interval=T2-T1
用Timer控件的确不准确,把Interval设为1时其实并不是1毫秒,而有10多毫秒了。我以前用的是下面这种方法:
Dim StartTime As Single
Private Sub Command1_Click()
StartTime = Timer '注意这里的Timer不是指的Timer控件,而是返回从零点开始所经过的秒数
End Sub
Private Sub Command2_Click()
Msgbox "从按Command1到按下Command2时共经过了" & Timer - StartTime & "秒。" '用当前的时间点减去按下Command1的时间点就等于时间差
End Sub
你试试这样行不?
上一个:需要一个VB自学全教程。
下一个:请教VB高手一个winsock的问题