请问我这代码为什么CPU占用率高?

「已注销」 2009-06-26 05:33:08
我最近学了一下MSDN里的用对象编程,试着写了一个类模块,虽然功能能用了,但CPU使用率比较高。请问应该怎样修改?

不要告诉我用Timer控件
...全文
60 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
cqcpl 2009-06-27
  • 打赏
  • 举报
回复
既然只是学习类模块而不是另找精确计时程序.建议如下

在窗体里放一Timer控件
在窗体中写
Private a As Class1
Private Sub Form_Load()
Set a = New Class1
a.Attach Timer1, Me, 500
End Sub

在类模块中写
Private WithEvents tmr As Timer
Private frm As Form

Public Sub Attach(Timer As Timer, Form As Form, lngInterval As Long)
Set tmr = Timer
Set frm = Form
tmr.Interval = lngInterval
End Sub

Private Sub tmr_Timer()
frm.Caption = Now
End Sub
mhm0517 2009-06-26
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20090527/11/439c51aa-0e80-4619-b956-a3431afe5a2c.html?46165

你参考一下.
「已注销」 2009-06-26
  • 打赏
  • 举报
回复
我这个代码的目的就是使用类模块实现计时器功能,然后在窗体里显示目前时间。我也知道那个Do...Loop比较占CPU,但我目前没办法,所以请指点。
贝隆 2009-06-26
  • 打赏
  • 举报
回复
Do
If Timer > Starttime + interval \ 1000 Then
RaiseEvent Jishi
Starttime = Timer
End If
If Qidong = False Then Exit Do
DoEvents
Loop
问题出在你的这个循环上,我暂时没有好的建议。
神马都能聊 2009-06-26
  • 打赏
  • 举报
回复

Private Sub Form_Paint()
Cls
Print Now

End Sub

一直在执行,你可以加断点看下
「已注销」 2009-06-26
  • 打赏
  • 举报
回复
类模块:

Option Explicit

Private Qidong As Boolean
Public interval As Single
Public Event Jishi()
Private Starttime As Single

Public Function Enable()
Qidong = True
Starttime = Timer
If Qidong = True And interval > 0 Then
Do
If Timer > Starttime + interval \ 1000 Then
RaiseEvent Jishi
Starttime = Timer
End If
If Qidong = False Then Exit Do
DoEvents
Loop
End If

'interval\1000是因为VB的Timer函数单位是秒,而我们要做的计时器单位是毫秒

End Function

Public Function Disable()
Qidong = False

End Function



Form1:

Option Explicit

'2009-6-26

Public WithEvents Jishiqi As Timerlei

Private Sub Command1_Click()
Set Jishiqi = New Timerlei
Jishiqi.interval = 1000
Jishiqi.Enable

End Sub

Private Sub Command2_Click()
Jishiqi.Disable

End Sub

Private Sub Form_Paint()
Cls
Print Now

End Sub

Private Sub Jishiqi_Jishi()
Form_Paint

End Sub

7,763

社区成员

发帖
与我相关
我的任务
社区描述
VB 基础类
社区管理员
  • VB基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧