簡體   English   中英

Perl中的C ++ regex_search與regex匹配

[英]C++ regex_search vs regex matching in perl

我有一個日志文件,其中包含40萬條日志行。 我發現,與perl代碼相比,我的c ++代碼非常慢。 因此,我對日志文件進行了簡單的迭代,並使用了c ++和perl的正則表達式。 Perl腳本的執行速度非常快,而c ++則需要時間。

在C ++中,我正在使用#include<regex>庫。 而在perl中,可以直接使用正則表達式。 如何使c ++代碼與perl一樣高效? 由於perl的實現僅由C實現。

regex log_line("(\\d{1,2}\\/[A-Za-z]{3}\\/\\d{1,4}):(\\d{1,2}:\\d{1,2}:\\d{1,2}).*?\".*?[\\s]+(.*?)[\\s\?].*?\"[\\s]+([\\d]{3})[\\s]+(\\d+)[\\s]+\"(.*?)\"[\\s]+\"(.*?)\"[\\s]+(\\d+)");
string line;
int count =0;
smatch match;
while(getline(logFileHandle, line){
    if(regex_search(line , match , log_line)==true){
    count++
}


open(N==LOG_FILE,"<$log_file_location");
        my $count=0;
        while($thisLine = <=LOG_FILE>){
            if((($datePart, $time, $requestUrl, $status, $bytesDelivered, $httpReferer, $httpUserAgent, $requestReceived) = $thisLine =~ /(\d{1,2}\/[A-Za-z]{3}\/\d{1,4}):(\d{1,2}:\d{1,2}:\d{1,2}).*?\".*?[\s]+(.*?)[\s\?].*?\"[\s]+([\d]{3})[\s]+(\d+)[\s]+\"(.*?)\"[\s]+\"(.*?)\"[\s]+(\d+)/o) == 8){
                $count++;
            }
        }

恐怕如果我的問題格式不正確或缺少某些內容,請通知我。 謝謝。

編輯1因此,我在C ++中使用了chrono庫來找出花費的時間。 以下是輸出結果。 為了方便起見,我抽取了一個日志文件樣本。 只需讀取日志文件並計數即可。 行需要57毫秒。 使用regex_search時,相同的示例日志文件要花費2462毫秒。

No of Lines27399
With regex + logfileRead
Time taken by function: 2462 milliseconds
No of Lines27399
With just simple logfileRead
Time taken by function: 57 milliseconds

使用代碼生成器工具(如re2cragel)將您的正則表達式編譯為C / C ++代碼(可由編譯器優化)。

另外, Boost.Regex (這是std :: regex的基礎)可能比std :: regex的實現要快。

同樣,瓶頸可能是I / O而不是正則表達式。 為什么在C ++中從stdin讀取行比Python慢​​得多?

在使用boost :: regex c ++代碼時,它像噴氣飛機一樣飛翔。 std :: regex尚未針對性能進行優化和優化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM