您的位置:首页 > 编程语言

Inventor API代码性能优化 - 1

2015-09-06 18:46 337 查看
好久没写Inventor方面的专题了。最近我们团队专家Brian写了篇很有深度的文章Improving Your Program’s Performance,专门谈到如何对Inventor API代码性能优化。借此机会翻译概要,供给各位参考。

首先,最好对性能有个量化的评估,到底有多慢。可以使用开发语言中的秒表。例如.NET里有StopWatch。

' Use the .Net StopWatch class to time an action. 
Dim stopwatch As New System.Diagnostics.Stopwatch 
stopwatch.Start()

' Do some things. 
' Get the time taken. 
MessageBox.Show("Elapsed time: " & _ 
                stopwatch.ElapsedMilliseconds / 1000 & " seconds")


VBA中有方法,但Brian实践中发现有时这个方法不能返回正确的时间。他一般用这个自定义类,例如名为 clsTimer

' clsTimer Definition. 
Private Declare PtrSafe Function QueryPerformanceFrequency _ 
         Lib "kernel32" (lpFrequency As Currency) As LongPtr 
Private Declare PtrSafe Function QueryPerformanceCounter _ 
         Lib "kernel32" (lpPerformanceCount As Currency) As LongPtr

Private ConversionFactor As Currency 
Private CurrentStartTime As Currency

Public Sub Start() 
    Dim iReturn As LongPtr 
    iReturn = QueryPerformanceCounter(CurrentStartTime) 
End Sub

Public Function GetTime() As Double 
    Dim NewTime As Currency 
    Dim iReturn As LongPtr 
    iReturn = QueryPerformanceCounter(NewTime) 
    
    Dim TotalTime As Currency 
    TotalTime = NewTime - CurrentStartTime 
    GetTime = TotalTime / ConversionFactor 
End Function

Private Sub Class_Initialize() 
    Dim iReturn As LongPtr 
    iReturn = QueryPerformanceFrequency(ConversionFactor) 
End Sub


接着您就可以用这个类来计算时间:

' Use the timer class to time an action. 
Dim timer As New clsTimer 
timer.Start 

' Do some things. 

' Get the time taken. 
MsgBox "Elapsed time: " & Format(timer.GetTime, "0.00000") & " seconds"


其实,在琢磨消耗时间之前,大前提是,您的应用程序是Inventor进程内的(插件)还是进程外(独立的EXE)。这里有个小测试,反复调用一个Inventor方法,进程内消耗0.24秒,进程外需要74.8秒。

Public Sub CallCost() 
    Dim timer As New clsTimer 
    timer.Start 

    Dim i As Long 
    For i = 1 To 100000 
        Dim code As Long 
        code = ThisApplication.Locale 
    Next 

    Debug.Print "Total time: " & Format(timer.GetTime, "0.00000") 
End Sub


当然上面的测试并不是简单的说进程内比进程外总是快74.8/0.24 = 312倍。但总体上,大多数场景,进程内比进程外要快,所以,如果您的是独立EXE,可考虑是否做成插件。学徒服务器也是独立EXE,它的调用效率要比单纯的启动Inventor的独立EXE要快些。

但有时我们不得不用进程外的方式,例如计划任务批处理,或者是一个Excel里的VBA宏,跨进程调用。那么我们还得从代码本身想想办法。

进程内比进程外要快些,其中一个因素是进程外把配置用户界面(Ribbon)消耗和其它调用分开,并且Ribbon的调用优先级较高。而进程外内的是把二者纳入到进程本身。可以通过设置UserInterfaceManager.UserInteractionDisabled 为true让程序不处理Ribbon方面的功能,尤其对于进程外的操作,一般不会和Inventor本身界面打交道。Brian测试发现,上面的压力测试,从78.4秒将变为61.32 秒,而且好些程序过程都有明显的提升。

Public Sub CallCost() 
    Dim timer As New clsTimer 
    timer.Start 

    app.UserInterfaceManager.UserInteractionDisabled = True 

    Dim i As Long 
    For i = 1 To 100000 
        Dim code As Long 
        code = ThisApplication.Locale 
    Next 

    app.UserInterfaceManager.UserInteractionDisabled = False 

    Debug.Print "Total time: " & Format(timer.GetTime, "0.00000") 
End Sub


注意做一些异常和错误的判断,及时恢复UserInteractionDisabled = false,避免因此造成其它环节的问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: