C++程序字符串的搜索速度是否比Python快?

2024-09-26 22:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

<>我不确定为什么我在Python中编写程序的时间字符串搜索比我在C++中写的程序快。有没有我错过的把戏?在

生成用例

这是针对单行用例的,但是在实际用例中,我关心多行。在

#include "tchar.h"
#include "stdio.h"
#include "stdlib.h"
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <ctime>

using namespace std;
void main(void){
   ofstream testfile;
   unsigned int line_idx = 0;
   testfile.open("testfile.txt");
   for(line_idx = 0; line_idx < 50000u; line_idx++)
   {
      if(line_idx != 43268u )
      {
        testfile << line_idx << " dontcare" << std::endl;
      }
      else
      {
        testfile << line_idx << " care" << std::endl;
      }
   }
   testfile.close();
}

正则表达式 使用正则表达式^(\d*)\s(care)$

<> >强> C++程序>13.954秒

^{pr2}$

Python程序耗时0.02200秒

^{3}$

Tags: 字符串程序includeline时间用例std单行
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:07

执行Ratah对8.923的建议

通过将文件读入单个字符串,大约5秒的时间提高

   double duration;
   std::clock_t start;
   ifstream testfile("testfile.txt", ios_base::in);
   unsigned int line_idx = 0;
   bool found = false;
   string line;
   regex ptrn("^(\\d*)\\s(care)$");
   std::smatch matches;

   start = std::clock();   /* Debug time */
   std::string test_str((std::istreambuf_iterator<char>(testfile)),
                 std::istreambuf_iterator<char>());

   if(regex_search(test_str, matches, ptrn))
   {
      found = true;
   }
   testfile.close();
   duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
   std::cout << "Found? " << (found ? "yes" : "no") << std::endl;
   std::cout << " Total time: " <<  duration << std::endl;

在UKMonkey的注释之后,将项目重新配置为发布,其中还包括\O2,并将其降低到0.086秒

感谢Jean Francois Fabre,Ratah,Ukmankey

相关问题 更多 >

    热门问题