メモ_正規表現の処理速度_簡単なベンチマーク_Pythonとc

ふと気になったので、正規表現の処理速度を簡単にベンチマークしてみました。

正規表現パターンr'\d{3}-\d{3}-\d{3}-\d{3}-\d{3}-\d{3}'と文字列'123-456-789-123-456-789'のマッチングを1000万回おこなって、その実行時間を計測して表示してます。

以下がコードと結果です。Python(Windows11,VM-Ubuntu22)、c(VM-Ubuntu22)の3つで比較してます。

 

Pythonのコード:

import re
import timeit

def regex_match():
    return re.match(r'\d{3}-\d{3}-\d{3}-\d{3}-\d{3}-\d{3}', '123-456-789-123-456-789')


if __name__ == '__main__':
    print('Benchmarking...')
    print('Regex match:', timeit.timeit(regex_match, number=10000000))
cのコード:

#include 
#include 
#include 
#include <sys/time.h>

int main() {
    regex_t regex;
    int ret;
    char *pattern = "[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]{3}-[0-9]{3}";
    char *string = "123-456-789-123-456-789";
    struct timeval start, end;
    double elapsed;

    ret = regcomp(&regex, pattern, REG_EXTENDED);
    if (ret) {
        fprintf(stderr, "Could not compile regex\n");
        return 1;
    }

    printf("Benchmarking...\n");

    gettimeofday(&start, NULL);
    for (int i = 0; i < 10000000; i++) {
        ret = regexec(&regex, string, 0, NULL, 0);
        if (ret == REG_NOMATCH) {
            fprintf(stderr, "No match\n");
            regfree(&regex);
            return 1;
        }
    }
    gettimeofday(&end, NULL);

    elapsed = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 10000000.0;

    printf("Regex match: %.6f seconds\n", elapsed);

    regfree(&regex);

    return 0;
}
結果:

以下のようになりました。cが一番速いのは当然として、Windows上でのPythonよりも、VM上のPythonのほうが速いのか。

VM上のUbuntu 22でのc: 1.98秒

VM上のUbuntu 22でのPython: 8.99秒

Wondows11上のPython: 11.29秒

環境

CPU : Ryzen7 5825U

MEM : 16GB

 

ホストOS: Windwos11 Home

Windows Python: conda 4.12.0 / Python 3.9.12

 

ホストOS(VM) : Virtual Box Version 7.0.6 / Ubuntu 22 LTS

VM Python: Python 3.9.16

VM gcc: 11.3.0