2016-10-06 3 views
-1

특정 길이의 가능한 모든 하위 문자열에 대해 일부 처리를 수행하는 프로그램이 있습니다. 가능한 한 빨리 프로그램을 만들려고 노력하고 있습니다. 나는 그것을 더 빨리 만들기 위해 다음 프로그램을 어떻게 할 수 있을지 궁금해하고있다.더 빠른 부분 문자열 처리 C++

char str[] = "abcdcddcdcdcdcd....................." // large string 
int n = strlen(str), m = 20; 
for(int i=0; i<n; i++){ 
    char *substr = (char*) malloc(sizeof(char)*m); 
    strncpy(substr, str+i, m); 
    // do some processing 
    int h = hd(substr, X) // X is another string of same length 
    free(substr); 
} 

unsigned int hd(const std::string& s1, const std::string& s2) 
{ 

    return std::inner_product(
     s1.begin(), s1.end(), s2.begin(), 
     0, std::plus<unsigned int>(), 
     std::not2(std::equal_to<std::string::value_type>()) 
    ); 
} 
+1

이것은 C++ 코드가 아닙니다. 실제로 평이한 c와 좀 더 비슷해 보입니다. –

+0

'malloc' 호출을 피하고 루프 외부에서 버퍼를 생성 할 수 있습니다. – Jarod42

+0

예,'string' 대신'char *'를 사용하고 있습니다. string'의'substr()'함수가 객체를 생성한다고 생각합니다. 따라서 큰 문자열에 대해서는 속도가 느려집니다. –

답변

0

훨씬 더 빠른 프로그램을 만든다.

char str[] = "abcdcddcdcdcdcd....................." // large string 
int n = strlen(str), m = 20; 
char *substr = (char*) malloc(sizeof(char)*m); 
for(int i=0; i<n; i++){ 
    //char *substr = (char*) malloc(sizeof(char)*m); 
    strncpy(substr, str+i, m); 
    // do some processing 
    int h = hd(substr, X) // X is another string of same length 
    //free(substr); 
} 
free(substr); 

unsigned int hd(const std::string& s1, const std::string& s2) 
{ 

    return std::inner_product(
     s1.begin(), s1.end(), s2.begin(), 
     0, std::plus<unsigned int>(), 
     std::not2(std::equal_to<std::string::value_type>()) 
    ); 
} 
2

아마도 이런 식이다. 현재의 부분 문자열의 포인터와 일치시킬 문자열의 길이를 전달함으로써 다중 문자열 처리를 피합니다. 루프 및 외부 mallocfree 이동시킴으로써

#include <stdio.h> 
#include <string.h> 

int hd(char *str, char *cmp, int len) 
// find hamming distance between substring *str and *cmp of length len 
{ 
    int ind, hamming = 0; 
    for(ind=0; ind<len; ind++) { 
     if(str[ind] != cmp[ind]) { 
      hamming++; 
     } 
    } 
    return hamming; 
} 

int main(void) 
// find hamming distance 
{ 
    char str[] = "abcdcddcdcdcdcd"; 
    char cmp[] = "abc"; 
    int lens = strlen(str); 
    int lenc = strlen(cmp); 
    int ind, max; 
    max = lens - lenc; 
    // analyse each possible substring 
    for(ind=0; ind<=max; ind++) { 
     printf("%d\n", hd(str + ind, cmp, lenc)); 
    } 
} 
+0

필자의 초기 구현에서 내가 작성한 것과 같은 자체 해밍 거리 함수를 사용하고있었습니다. 하지만 필자는 두 가지'char *'함수를 사용했다. 그러나'정적 인라인 int hd (unsigned x, unsigned y)'를 사용하면 속도가 빨라졌습니다. 나는 당신의 접근 방식과 프로그램을'for' 루프 이전에'malloc'으로 시도했지만'hd()'함수로 시도했습니다. 나중 프로그램이 빠릅니다. –

+0

이'hd' 함수도''inline' 할 수 있습니다. –

+0

어떻게 할 수 있습니까? 나는 그것을 빨리 할 수 ​​있다고 믿는다. –