// Author: Pete Kirkham // string match benchmark - block io, built-in string match algorithm. #include #include #include #include #include #define BLOCK_SIZE 8096 // naive string search size_t string_search (const char* pattern, size_t pattern_length, const char* string, size_t string_length) { const char first(pattern[0]); const size_t last_index(string_length - pattern_length); for (size_t index(0); index < last_index; ++index) if ((first == string[index]) && (strncmp(pattern, string + index, pattern_length) == 0)) return index; return string_length; } // process a line of input inline void process_line (size_t& matches, const char* pattern, size_t pattern_length, const char* line, size_t line_length) { // index of start of match // all lines start with x.x.x.x - - [DD/MMM/YYY:HH:MM:SS -0700] "GET // so we could start 34 chars into the line size_t index(string_search(pattern, pattern_length, line, line_length) + pattern_length); while (index < line_length) { char ch(line[index]); if ((ch == '.') || (ch == '\n')) break; if (ch == ' ') { ++matches; break; } ++index; } } // main int main (int narg, char** argvp) { if (narg < 2) { std::cout << "The name of the input file is required." << std::endl; return 1; } // open the file int file(open(argvp[1], O_RDONLY)); if (!file) { std::cout << "failed to open " << argvp[1] << std::endl; return 2; } // pattern to find const char* pattern("GET /ongoing/When/"); size_t pattern_length(strlen(pattern)); // block IO // for splitting lines, we move any trailing part line to the start of // memory then read data into the area following it char buf[BLOCK_SIZE*2]; ssize_t bytes_read; size_t bytes_carried(0); // count of matching lines size_t matches(0); // count of matching lines size_t lines(0); while ((bytes_read = read(file, buf + bytes_carried, BLOCK_SIZE)) > 0) { size_t chunk_length(bytes_carried + bytes_read); size_t line_start(0); // scan for line breaks for (size_t i(0); i < chunk_length; ++i) { if (buf[i] == '\n') { size_t line_length(i - line_start); const char* line(buf + line_start); #ifdef ECHO_LINES buf[i] = '\0'; std::cout << buf + line_start << std::endl; #endif ++lines; process_line(matches, pattern, pattern_length, line, line_length); line_start = i+1; } } // copy trailing data to start of alternate block // assumes that a line is never more than half a block long bytes_carried = chunk_length - line_start; memcpy(buf, buf + line_start, bytes_carried); } // if there is any last line, process that if (bytes_carried) { ++lines; process_line(matches, pattern, pattern_length, buf, bytes_carried); } close(file); std::cout << "matches: " << matches << std::endl; return 0; }