Skip to content
This repository was archived by the owner on Jan 28, 2026. It is now read-only.
This repository was archived by the owner on Jan 28, 2026. It is now read-only.

Compile time regex for C++ #37

Description

@bstaletic

I've just tried CTRE on these benchmarks. On my machine, it beats rust.

Here's the code:

#include "ctre.hpp"
#include <array>
#include <chrono>
#include <fstream>
#include <iostream>
#include <numeric>

template<size_t N>
void measure(const std::string& data) {
  using clock = std::chrono::high_resolution_clock;
  const auto start = clock::now();
  unsigned count = 0;
  if constexpr ( N == 0 )
    // Email
    for(auto match : ctre::range<"[\\w.+\\-]+@[\\w.\\-]+\\.[\\w.\\-]+">(data)) count++;
  else if constexpr ( N == 1 )
    // URI
    for(auto match : ctre::range<"[\\w]+:\\/\\/[^\\/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?">(data)) count++;
  else
    // IP
    for(auto match : ctre::range<"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])">(data)) count++;

  const auto end = clock::now();
  const double elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() * 1e-6;
  std::cout << elapsed << " - " << count << "\n";
}

int main(int argc, char** argv) {
  if (argc != 2) {
    std::cerr << "Usage: benchmark <filename>\n";
    return 1;
  }

  std::ifstream file{argv[1]};
  if (!file) {
    std::cerr << "unable to open " << argv[1] << "\n";
    return 1;
  }

  const std::string data{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};

  measure<0>(data);
  measure<1>(data);
  measure<2>(data);
}

CTRE is different from other C++ regex libraries in that it computes the state machine at compile time. The hard part about submitting a CTRE pull request for this repo is that it isn't packaged for Ubuntu. On my machine I have just downloaded the header straight from raw.githubuserconent.com with wget. The API is also completely different, so I don't know if I should make a new file for the PR or...

Also, it needs GCC 9.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions