使用for循环优化大数据比较

时间:2012-11-14 18:55:29

标签: .net vb.net algorithm optimization

好的,这是交易人员。我有two text files。每个包含500行(句子)。

我已将它们加载到memory到它们自己的数组中(数据类型:字符串)。我们将array A & B命名为

接下来,我在first sentence中获取array A,使用array C作为分隔符将其拆分为另一个SPACE,以便获取字词。

然后,对于array B中的每个句子,我再次使用array D作为分隔符将其拆分为SPACE以获取字词,并将array C中的每个字词与每个字词进行比较在array D中计算两个句子之间的百分比匹配。

我计算array A中第一句与array B中所有句子的平均百分比匹配。

然后我将其存储到Array E中,其中包含array A的所有句子及其平均匹配百分比。

我使用上面的first sentence对数组A中的每个标题执行操作。

问题在于,处理阵列A中的每个标题大约需要15秒。无论如何,我可以优化这段时间以加快速度吗?

硬件: AMD Phenom I 32位四核

CODE:

Imports System.IO
Imports System.Object
Imports System.Xml
Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
        'Important File Paths
        Dim titlesFilePath As String = Environment.CurrentDirectory & "\titles.txt"
        Dim xmlTitlesFilePath As String = Environment.CurrentDirectory & "\extractedTitles.txt"
        Dim stopWordsFilePath As String = Environment.CurrentDirectory & "\stopWords.txt"

        'Import Important Data From Files -> Memory
        Dim titles As Array = FileToArray(titlesFilePath)
        Dim stopWords As Array = FileToArray(stopWordsFilePath)
        Dim xmlDataUnprocessed As Array = FileToArray(xmlTitlesFilePath)

        'Delimters To Filter Titles For
        Dim userDefinedDelimeters(4, 1)

        userDefinedDelimeters(0, 0) = "-"
        userDefinedDelimeters(0, 1) = " "

        userDefinedDelimeters(1, 0) = ","
        userDefinedDelimeters(1, 1) = " "

        userDefinedDelimeters(2, 0) = "—"
        userDefinedDelimeters(2, 1) = " "

        userDefinedDelimeters(3, 0) = "'s"
        userDefinedDelimeters(3, 1) = ""

        userDefinedDelimeters(4, 0) = "'"
        userDefinedDelimeters(4, 1) = " "

        'Declare Important Variables
        Dim xmlData(xmlDataUnprocessed.Length / 2, 1)
        Dim xmlTurn = 0
        Dim xmlDataCount = 0

        'Create Feed Title/URL Array
        For i = 0 To (xmlDataUnprocessed.Length - 1)
            If xmlTurn = 0 Then
                xmlData(xmlDataCount, 0) = xmlDataUnprocessed(i)
                xmlTurn = 1
            Else
                xmlData(xmlDataCount, 1) = xmlDataUnprocessed(i)
                xmlTurn = 0

                xmlDataCount += 1
            End If
        Next


        'CPU-Intensive Stuff Occurs
        Dim xmlTitle As String
        Dim xmlTitleWords As Array
        Dim savedTitleWords As Array
        Dim titleResults(xmlData.GetUpperBound(0) - 1, 1)
        Dim titlePercentageMatch As Integer
        Dim numberOfTitlesMatched As Integer


        For i = 0 To xmlData.GetUpperBound(0) - 1
            Console.WriteLine("Working On Title No. " & i & " Out Of " & xmlData.GetUpperBound(0) - 1)
            titlePercentageMatch = 0
            numberOfTitlesMatched = 0

            xmlTitle = xmlData(i, 0)
            xmlTitle = processTitle(stopWords, userDefinedDelimeters, xmlTitle)
            xmlTitleWords = xmlTitle.Split(" ")

            For Each title In titles
                title = processTitle(stopWords, userDefinedDelimeters, title)
                savedTitleWords = title.split(" ")
                Dim compareResult = compareTitle(xmlTitleWords, savedTitleWords)
                If compareResult > 0 Then
                    titlePercentageMatch += compareResult
                    numberOfTitlesMatched += 1
                End If
            Next

            titleResults(i, 0) = xmlData(i, 0)
            titleResults(i, 1) = (titlePercentageMatch / numberOfTitlesMatched)
        Next

        For i = 0 To titleResults.GetUpperBound(0) - 1
            Console.WriteLine(titleResults(i, 0) & " ---> " & titleResults(i, 1) & vbCrLf)
        Next

        Console.Read()
    End Sub

    Function compareTitle(ByRef xmlTitleWords As Array, ByRef savedTitleWords As Array)
        Dim NumberOfMatches = 0

        For Each xmlWord In xmlTitleWords
            For Each savedWord In savedTitleWords
                If (xmlWord.ToString.ToLower = savedWord.ToString.ToLower) Then
                    NumberOfMatches += 1
                End If
            Next
        Next

        Return ((NumberOfMatches / xmlTitleWords.Length) * 100)
    End Function

    Function processTitle(ByRef stopWordArray As Array, ByRef delimArray As Array, ByVal title As String)
        title = removeStopWords(stopWordArray, title)
        title = removeDelims(delimArray, title)

        Return title
    End Function

    Function removeStopWords(ByRef stopWordsArray As Array, ByVal sentence As String)
        For i = 0 To stopWordsArray.Length - 1
            If sentence.ToLower.Contains(" " & stopWordsArray(i).ToString.ToLower & " ") = True Then
                sentence = Microsoft.VisualBasic.Strings.Replace(sentence, " " & stopWordsArray(i) & " ", " ", 1, -1, Constants.vbTextCompare)
                'ElseIf sentence.ToLower.Contains(stopWordsArray(i).ToString.ToLower & " ") = True Then
                'sentence = Microsoft.VisualBasic.Strings.Replace(sentence, stopWordsArray(i) & " ", "", 1, -1, Constants.vbTextCompare)
            End If

            sentence = Regex.Replace(sentence, "\s+", " ")

            Dim Words = sentence.ToLower.Split(" ")

            If Words(0).ToString.ToLower & " " = stopWordsArray(i).ToString.ToLower & " " Then
                sentence = sentence.Remove(0, stopWordsArray(i).ToString.ToLower.Length + 1)
            End If

            Words = sentence.ToLower.Split(" ")
            Dim LastWord = Words(Words.Length - 1)
            'Console.WriteLine(LastWord & "++")

            If " " & LastWord.ToString.ToLower = " " & stopWordsArray(i).ToString.ToLower Then
                sentence = sentence.Remove(sentence.Length - 1 - LastWord.Length, stopWordsArray(i).ToString.ToLower.Length + 1)
            End If

        Next

        sentence = Regex.Replace(sentence, "\s+", " ")

        Return sentence
    End Function

    Function removeDelims(ByRef delimArray As Array, ByVal sentence As String)
        For i = 0 To delimArray.GetUpperBound(0) - 1
            sentence = sentence.Replace(delimArray(i, 0), delimArray(i, 1))
        Next
        sentence = Regex.Replace(sentence, "\s+", " ")
        Return sentence
    End Function

    Function FileToArray(ByVal filePath As String) As String()
        Dim content As String
        Dim lines As New ArrayList
        Dim sr As System.IO.StreamReader

        ' read the file's lines into an ArrayList
        Try
            sr = New System.IO.StreamReader(filePath)
            Do While sr.Peek() >= 0
                lines.Add(sr.ReadLine())
            Loop
        Finally
            If Not sr Is Nothing Then sr.Close()
        End Try

        ' convert from ArrayList to a String array
        Return CType(lines.ToArray(GetType(String)), String())
    End Function

End Module

编辑:我希望它不会太混乱。对于那个很抱歉! 编辑2:提供酱:P

3 个答案:

答案 0 :(得分:2)

您的基本算法是 N * M * A 2 其中

  • N =第一个文件中的标题数
  • M =第二档中的标题数
  • A =每个标题的平均字数

如果您有500 * 500 * 5 2 ,那么您将推动6,250,000个不区分大小写的字符串比较。但那就是你所做的一切。您的内部循环通过外部循环的长度为每个processTitle调用title。它不需要这样做。

单线程

你可以做的是有一个预处理步骤,用表示该单词的整数(符号)替换每个单词。为此,您将使用字典来查找符号,如果没有,则分配一个新的唯一符号(例如,保留一个整数计数器并使用下一个值)。

然后你的主处理循环类似于你以前的处理循环,但你做的是整数比较(更快)。实际上,您希望此处理步骤进行比较和统计信息收集。其他一切都应该搬出去。

多线程

保持预处理步骤。

并行处理您的处理步骤。一种方法是使用Parallel.For()作为最外层循环:Parallel.For(0, xmlData.GetUpperBound(0) - 1, Sub(i) ... End Sub)其中action是从上面开始的循环体。 TPL可能会很好地平衡负载(均匀地使用4个核心)。

另一种方法是使用任务并行库来启动对1/4数据进行操作的任务。然后开始使用结果的延续。

答案 1 :(得分:1)

立即只读取array B内存,然后逐行读取array A

适用时使用StringBuilder而不是string。

另外,看看你是否可以使用并行处理,即:任务。

至于距离,匹配算法,你没有提到它是什么以及它是如何做的。很难说出来。

答案 2 :(得分:1)

你用一些东西减慢了自己的速度......

  1. If (xmlWord.ToString.ToLower = savedWord.ToString.ToLower) Then

    为什么不把所有内容改成小写,然后再把它放入数组呢?

  2. title = processTitle(stopWords, userDefinedDelimeters, title)

    为什么不在将它加载到数组之前这样做?

  3. 提前完成所有处理,然后单独进行比较。