text stringlengths 1 2.12k | source dict |
|---|---|
python, multithreading
We don't like , shell=True ?
OK. Perhaps there are filename quoting concerns.
Write a def which_convert(): helper that asks the
shell to consult $PATH and report what $ which convert says.
Decorate it with
@lru_cache.
check child exit value
Rather than proc = subprocess.run( ... ),
you might prefer .check_call( ... ).
The status integer is different from determining whether stderr
is of greater than zero length.
There's more than one "static gallery generator" available.
It would be helpful for a comment paragraph (or URL)
to offer an elevator pitch.
Why is this generator a better choice?
For which use case is it better?
What deficiencies of competing libraries does it remedy?
This codebase appears to achieve its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45490,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, multithreading",
"url": null
} |
c++, performance, rcpp, loops
Title: Performing tasks on for-loop over thousands of items in Rcpp
Question: I am trying to adapt an R script that I wrote to perform several tasks in a for-loop. The for-loop run over thousands of items, for about 900 times, therefore I would like to optimise my code at the best. I decided to go for c++ via Rcpp.
Here it is my code:
cppFunction('
Rcpp::DataFrame FasterFunction(StringVector path_data, IntegerVector ID_vector, const DataFrame& DF1,
DataFrame DF2, int time1, int time2, int start_time) { | {
"domain": "codereview.stackexchange",
"id": 45491,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, rcpp, loops",
"url": null
} |
c++, performance, rcpp, loops
Function read_t("fread");
Function subset("[.data.frame");
Function mergeDFs("merge");
const int& TimeVal = (time1 + time2 - (2 * start_time));
for(int i = 0; i < ID_vector.size(); ++i) {
int ID = ID_vector[i];
//Define path to file
StringVector tmp_path_data = path_data;
tmp_path_data.insert(1, "/prefix_");
tmp_path_data.insert(2, std::to_string(ID));
tmp_path_data.insert(3, ".txt");
Rcpp::String res = collapse(tmp_path_data);
//Read file as DataFrame
Rcpp::DataFrame data_df = read_t(Named("file")=res);
//Extract column "name1" from DataFrame "data_df"
Rcpp::NumericVector name1_list = as<NumericVector>(data_df["name1"]);
//Convert int to NumericVector
NumericVector ID_vec(1);
ID_vec[0] = static_cast<double>(ID);
//Finding "ID_vec" matching value in "name1_list" vector
IntegerVector ID_pos = match(ID_vec,name1_list);
//Remove row from "data_df" with "ID" in column "name1"
data_df = subset(data_df, -ID_pos,R_MissingArg);
//Extract column "name1" from DataFrame "data_df", after removing "ID"
name1_list = as<NumericVector>(data_df["name1"]);
//Extract column "name1" from DataFrame "DF2"
Rcpp::NumericVector ID2_list = as<NumericVector>(DF2["name1"]);
//Finding "name1_list" matching value in "ID2_list" vector
IntegerVector ID2_pos = match(name1_list,ID2_list);
//Remove rows from "DF2" with "ID2_pos" in column "name1"
Rcpp::DataFrame tmpDF = subset(DF2, ID2_pos,R_MissingArg);
//Merge "data_df" and "DF2" by column "name" "ID2_pos" in column "name1"
const DataFrame& resDF = mergeDFs(Named("x")=data_df,Named("y")=DF2,Named("by")="name1");
//Add additional columns to the "resDF" dataframe
resDF["term1"] = abs(as<NumericVector>(resDF["factor1"]) - as<NumericVector>(resDF["factor2"]));
resDF["term2"] = Rcpp::pow((1 - as<NumericVector>(resDF["term1"])),TimeVal);
//Add values to row "i" and column "term_tot" of the dataframe "DF1" | {
"domain": "codereview.stackexchange",
"id": 45491,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, rcpp, loops",
"url": null
} |
c++, performance, rcpp, loops
//Add values to row "i" and column "term_tot" of the dataframe "DF1"
Rcpp::NumericVector TermTot_Vector = as<NumericVector>(DF1["term_tot"]); | {
"domain": "codereview.stackexchange",
"id": 45491,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, rcpp, loops",
"url": null
} |
c++, performance, rcpp, loops
TermTot_Vector[i] = sum(as<NumericVector>(resDF["term2"]));
DF1["term_tot"] = TermTot_Vector;
};
return(DF1);
};
')
As an example to what ID_vector, DF1, DF2 and data_df correspond to, consider the following:
ID_vector = c(1,3,5,9,13,14,22,39)
DF2 = data.frame(name1 = c(1,3,5,9,13,14,22,39), factor2 = rnorm(8,0,2))
DF1 = data.frame(name1 = c(1,3,5,9,13,14,22,39), term_tot = rep(NA,8))
data_df = data.frame(nameA = rep(3,8),name1 = c(1,3,5,9,13,14,22,39), factor1 = rnorm(8,0,1))
Note that I did not provide the path_data argument for reproducibility, since it woudl require the long list of files over which the for-loop goes. However, the structure of the data within the files is given by the data_df dataframe. There, I would be mostly interested in knowing wether I am reading the file in the more efficient way. | {
"domain": "codereview.stackexchange",
"id": 45491,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, rcpp, loops",
"url": null
} |
c++, performance, rcpp, loops
Answer: Inconsistent use of Rcpp::
You are not using Rcpp:: consistently. Either use it everywhere or don't use it at all.
What does everything mean?
FasterFunction() is a very bad name for a function. The word Function is redundant, and Faster is also not very informative: faster than what? Faster how?
Many variable names are also not helpful at all. What are DF1 and DF2? I already know from the type that they are dataframes, so DF is not adding any more information. And there are two, but what is the difference between them?
Even the column names in the dataframes are very generic. factor1, term1? Reading this code doesn't give me any clue about what is in these dataframes, nor what it is that you are trying to calculate.
Unless you intentionally obfuscated the code when posting it here on Code Review (which you shouldn't anyway), please spend some time giving all the functions, variables and dataframe columns meaningful names. It's not just me that can't understand the code you have written, your colleagues might also have trouble, and even you yourself, after one year, will have forgotten half of what you wrote here, so it's in your own interest to do this.
Some rules of thumb: | {
"domain": "codereview.stackexchange",
"id": 45491,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, rcpp, loops",
"url": null
} |
c++, performance, rcpp, loops
Use nouns for variables, verbs for functions. For example, subset is a bad name for a function. make_subset would be better, but how exactly does it decide what subset to make? The comment above its use says it removes rows. Maybe that should be reflected in the name.
Don't put the type of something in its name. Don't append things like _vector, _list, and _df to the names of variables. The type of the variable will already clarify what it is. For variables that hold multiple values, make their name a plural, so for example IDs instead of ID_vec.
Be consistent. I see _vec, _Vector, and _list being used as suffixes for things that are NumericVectors. If you are going to use some suffix, make sure you pick one and use it consistently. Also pick one style of capitalization for variable names, so write term_tot instead of TermTot.
Don't abbreviate unnecessarily. What does pos mean? Position? Positive? Posit? Prefer to write words in full. If you do abbreviate, make sure you use the same abbreviation consistently, and that it is not creating any ambiguities.
Avoid generic and meaningless words. tmp? Sure it is a temporary variable, but what does it hold?
Remove as much as you can out of the loop
Find whatever you can that is done within the loop that you can do outside of it, as that will prevent the same thing from being done multiple times unnecessarily. For example:
tmp_path_data: you can already build and collapse everything up to and including "/prefix_", and only add the ID and .txt inside the loop.
TermTot_Vector can be declared before the loop, and DF1["term_tot"] = TermToT_Vector can be done after the loop.
There might be many more things that can be optimized this way.
Remove dead code
You calculate tmpDF but then you never use it. | {
"domain": "codereview.stackexchange",
"id": 45491,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, rcpp, loops",
"url": null
} |
c++, beginner, programming-challenge
Title: Advent of Code 2023 day 1: Trebuchet (Part 1)
Question: Task:
The task involves analyzing a calibration document containing lines of text. Each line represents a calibration value that needs to be recovered by extracting the first and last digits and combining them into a two-digit number. The goal is to find the sum of all these calibration values.
For example:
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.
Code:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <system_error>
static int calibration_total(std::ifstream &in_file) noexcept
{
const std::string accept{"0123456789"};
int sum{};
std::string line{};
/* This is not very pedantic, we are assuming that the methods
* would never return `npos`.
*/
while (std::getline(in_file, line)) {
int first_digit{line[line.find_first_of(accept)] - '0'};
int last_digit{line[line.find_last_of(accept)] - '0'};
sum += first_digit * 10 + last_digit;
}
return sum;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
std::cerr << "Usage: " << (argv[0] ? argv[0] : "") << " <filename>\n";
return EXIT_FAILURE;
}
std::ifstream in_file{argv[1]};
if (!in_file.is_open()) {
std::cerr << "Error: failed to open " << argv[1] << " - "
<< std::error_code{errno, std::generic_category()}.message()
<< ".\n";
return EXIT_FAILURE;
}
const int sum{calibration_total(in_file)};
if (!in_file.eof()) {
std::cerr << "Error: failed to read input file " << argv[1] << " - "
<< std::error_code{errno, std::generic_category()}.message()
<< ".\n";
return EXIT_FAILURE;
}
std::cout << sum << "\n";
in_file.close();
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 45492,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
std::cout << sum << "\n";
in_file.close();
return EXIT_SUCCESS;
}
Review Request:
General coding comments, style, bad/outdated practices et cetera.
Answer: This looks very good, you have paid attention to many details. I especially appreciate the correct way to handle input errors. Still, a few things can be improved:
Remove noexcept
std::getline() is not noexcept, so it is possible that exceptions will be thrown, for example if it needs to resize line but you are out of memory. By adding noexcept you now prevent the caller from handling any exceptions thrown inside calibration_total().
There is also no benefit whatsoever from making this function noexcept. I recommend that you avoid adding noexcept to things, unless you really know that it might give a performance benefit.
Efficiency
The call to find_last_of() starts from the beginning of the line, but you already know where the first digit is. You can use the result of find_first_of() and only pass a substring starting at that position to find_last_of(), that avoids doing some work twice. Of course, making a substring is expensive in itself, but you can avoid that by using std::string_views.
It might be faster to use std::ranges::find() and std::ranges::find_end() with std::isdigit() as the predicate, as that avoids scanning the string accept for every character in line.
Print something useful if !argv[0]
If argv[0] is nullptr, you print an empty string for the program name. That's not very nice, it will then print:
Usage: <filename> | {
"domain": "codereview.stackexchange",
"id": 45492,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
I would just print the most likely name the binary will have.
Unnecessary statements
The statement in_file.close() is unnecessary; a std::ifstream object will close itself automatically when its scope ends.
You also don't need return EXIT_SUCCESS at the end of main(), although it's not wrong.
Finally, the test for in_file.is_open() is also not really necessary; if it wasn't opened, then calibration_total() will immediately exit, and in_file.eof() will still be false, so you are still printing an error message in that case. | {
"domain": "codereview.stackexchange",
"id": 45492,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, parsing
Title: Natural language text fast tokenizer (Rev.5)
Question: This is the next iteration of the Natural language text fast tokenizer code review. Special thanks goes to G. Sliepen, Toby Speight and uli who conducted previous reviews and to Matthieu M. and Adrian McCarthy who participated with important findings.
Functional specification
Implement a class for fast text tokenization handling some natural language specifics below:
Consider ‘ ‘ (space) as a delimiter, keeping a way to extend the list of delimiters later; the delimiters couldn’t be a part of other constructs.
Extract stable collocations like “i.e.”, “etc.”, “…” as a single lexem.
In case word contains “inword” characters like ‘-‘ and ‘’’ (examples: semi-column, half-, cat’s) return the whole construct as a whole lexem.
Threat all other non-alphanumeric characters as separate lexems.
Return sequences of numbers (integers without signs) as a single lexem.
Consider out of scope paired quotes and other lexical parsing level issues.
Performance is critical, since the amount of data is huge. The function should be thread-safe.
Changes
The code has been reworked according to all code review points.
Reservations
Methods implementation inside of the class definition done only to the sake of brevity; production code will have them implemented separately.
I am not sure that using value_type = std::string_view; is correct in TokenRange::Iterator; most likely I should store a nested struct for data and lexem and it should be a type of value_type, but I pretend like lexem is the value to be stored and data is some proxy of TokenRange::data which makes the iterator safer in case of TokenRange changes. At the end of the day, both TokenRange::data and TokenRange:: Iterator::data are just proxies to the original std::string / std::string_view passed to TokenRange. | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
The code
Here is the updated code for the code review; could you please take a look and suggest further ways to improve or confirm that this is ready to go code?
Fully functional demo.
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstring>
#include <functional>
#include <iostream>
#include <limits>
#include <locale>
#include <numeric>
#include <random>
#include <ranges>
#include <vector>
namespace fast {
template <typename Fn>
class CharacterClass
{
std::array<char, std::numeric_limits<char>::max() + 1> cache = {};
public:
explicit CharacterClass(Fn fn, const std::locale& locale = {})
{
set_locale(fn, locale);
}
void set_locale(Fn fn, const std::locale& locale)
{
auto const func = [&locale, &fn](char c) { return fn(c, locale); };
std::ranges::copy(std::views::iota(0u, cache.size())
| std::views::transform(func),
cache.begin());
}
bool operator()(char c) const { return cache[c]; }
};
CharacterClass isalpha(std::isalpha<char>);
CharacterClass isdigit(std::isdigit<char>);
CharacterClass isalnum(std::isalnum<char>);
}
class TokenRange {
std::string_view data;
public:
class Iterator {
const std::string_view delimiters = " ";
const std::vector<std::string_view> stable_lexems = { "...", "i.e.", "etc.", "etc..." };
const std::string_view inword_symbols = "-\'";
std::string_view data;
std::string_view lexem;
public:
using iterator_category = std::input_iterator_tag;
using value_type = std::string_view;
using difference_type = std::ptrdiff_t; | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
Iterator() {}
Iterator(std::string_view data) : data(data) { extract_lexem(); }
std::string_view operator*() const { return lexem; }
Iterator& operator++();
Iterator operator++(int);
friend bool operator==(const Iterator& it1, const Iterator& it2) { return it1.lexem == it2.lexem; }
friend bool operator!=(const Iterator& it1, const Iterator& it2) { return it1.lexem != it2.lexem; }
Iterator& operator=(const Iterator& it) { data = it.data; lexem = it.lexem; return *this; }
private:
void extract_lexem();
void skip_delimiters();
bool check_for_stable_lexems();
};
TokenRange(std::string_view data) : data(data) {}
Iterator begin() const {
return Iterator(data);
}
Iterator end() const {
return {};
}
};
void TokenRange::Iterator::skip_delimiters()
{
while (!data.empty() && std::ranges::contains(delimiters, data.front())) {
data.remove_prefix(1);
}
}
bool TokenRange::Iterator::check_for_stable_lexems()
{
auto it = std::ranges::max_element(stable_lexems, std::less<size_t>(),
[&](auto stable_lexem) {
return data.starts_with(stable_lexem) ? stable_lexem.size() : 0;
}
);
if (it != stable_lexems.end() && data.starts_with(it->data()) ) {
lexem = data.substr(0, it->size());
data = data.substr(it->size());
return true;
}
return false;
}
void TokenRange::Iterator::extract_lexem()
{
skip_delimiters();
if (check_for_stable_lexems()) {
return;
}
std::size_t index = 0;
while (index < data.size())
{
if (std::ranges::contains(delimiters, data[index])) {
break;
}
if (!fast::isalnum(data[index])) {
if (index == 0) {
++index;
}
break;
} | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
const bool is_next_char_inword_symbol = (index+1) < data.size() ? std::ranges::contains(inword_symbols, data[index+1]) : false;
if (is_next_char_inword_symbol) {
++index;
}
++index;
}
lexem = data.substr(0, index);
data = data.substr(index);
}
TokenRange::Iterator& TokenRange::Iterator::operator++()
{
extract_lexem();
return *this;
}
TokenRange::Iterator TokenRange::Iterator::operator++(int)
{
Iterator temp(data);
extract_lexem();
return temp;
}
int main()
{
{
std::string sample = "Let's consider, this cats' semi-simple sample, i.e. test data with ints: 100 and 0x20u, etc. For ... some testing...";
for (auto token : TokenRange(sample)) {
std::cout << token << " | ";
}
}
#define TEST_SUITE
#ifdef TEST_SUITE
struct {
std::string input;
std::vector<std::string> expected;
} samples[] = {
{ "", {} },
{ " ", {} },
{ " ", {} },
{ "etc.", { "etc." } },
{ "etc.i.e.", { "etc.", "i.e."} },
{ "...etc...", { "...", "etc..."} },
{ "......", { "...", "..." } },
{ "....", { "...", "." } },
{ ".,:", { ".", ",", ":"}},
{ "cat\'s cats\' 'cats'", { "cat\'s", "cats\'", "\'", "cats\'"}},
{ "semi-semi-column", { "semi-semi-column" } },
{ "Let's consider, this cats' semi-simple sample, i.e. test data with ints: 100 and 0x20u, etc. For ... some testing...",
{ "Let\'s", "consider", ",", "this", "cats\'", "semi-simple", "sample", ",", "i.e.", "test", "data", "with", "ints", ":", "100", "and", "0x20u", ",", "etc.", "For", "...", "some", "testing", "..." } },
};
for (auto& sample : samples) {
assert(std::ranges::equal(TokenRange(sample.input), sample.expected));
}
#endif // TEST_SUITE
} | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
Some final thoughts
I started with 48 lines of very simple (in terms of used language techniques) code which fit a C-style function and ended up with two sophisticated classes (well, at least one of them) of 110 lines of code whose behaviour is not so obvious and transparent for a newbie developer or another person in support.
The code was improved and some subtle defects were fixed, but all this could have been done in scope of the original function and would led even to reducing its size.
I have some personal profits:
I learned a lot about ranges, concepts and compiler warnings for them.
I learned a technique to distribute work between ‘operator++()’ and ‘operator*()’ in iterators.
I got the prove that std::string_view and some other tools used here in no meaning slower that traditional C-style pointers.
I got another confirmation that “working” code without unit tests doesn’t go.
So, all this comes as experience and I am thankful for all people involved here.
On the other hand, if we consider the task “as is”, here are my thoughts.
Profits
Now the code supports (at least preliminary and partially) new language technique, namely, std::ranges.
The API became much safer without char * and friendlier to the user with support of iterators and ranges.
Drawbacks | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
Drawbacks
The code became longer and harder to maintain. This especially comes with this state machine data / lexem.
It is very hard to prove that code is still correct not only terms of tokenizing, but even in terms of usage C++ for iterators; many things done as “well, this works” and require very detailed reading of standard on iterators, ranges, concepts, requires’, etc. to make sure that this code fits all these requirements. So, this again increases requirements to personnel who will develop and support the code, while the original technical specification never required this.
The code no more portable to C language fast, if needed. I remember that I myself asked in the first post to use std::ranges, but I meant to use some functions which could be easily replaced back with C-style functions, not to implement this object as std::range itself. | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
This is always a design choice which way to go, to solve the specific task in existing code or to improve it with continuous refactoring. In my personal view, the main programmer’s mistake is to solve a wrong task and if initial functional specification told “Implement a function” and programmer started with expensive refactoring to iterators, ranges, etc. I would consider this as overengineering and spending effort aimlessly. If instead of fixing some lines of code in function they would develop two classes, I would consider this a mistake, since technical requirements never asked to implement something different and the client could be constrained with function usage (although, I would agree that code review title could give such a freedom). And the key point is that after first turn of code review I agreed with the proposal, so accepting the design decision is on me and I am totally responsible here. So, I am considering my choice in retrospective to learn.
And please, don’t get me wrong, I am very thankful to G. Sliepen who suggested this way and helped me learn a lot in practice and I am not saying that he suggested a wrong design decision; I believe, his circumstances and goals was slightly different, namely to show on this simple example how to develop good nowadays C+ software and he succeeded here. My only concern if this specific small task is a good candidate for this since it mixes two questions: good language style and a very specific task. My point is that the technique is great, but it is arguable that this particular task benefits from it taking into account the drawbacks.
To be precise in wording:
Should the proposed style be used instead of old one? Yes, in most of the cases.
Should the developer given the original task start this refactoring instead of fixing defects in the function? I am not sure, totally depends on the context and how it will be used | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
So, to put in a nutshell, I am still in twenty minds about this refactoring for this specific task, although I consider it “must learn to use when needed”.
Please, don’t consider this as concerns, complains or disagreements, this is just thoughts to share. Thank you all, who helped me here!
Answer: Enable compiler warnings and fix them
When developing code, always enable rather strict compiler warnings (for example, using -Wall -W -pedantic for Clang and GCC, but you could go even stricter at the risk of getting false positives). Whenever the compiler warns about something, don't ignore it but fix it. Both Clang and GCC complain about this:
In member function 'TokenRange::Iterator TokenRange::Iterator::operator++(int)':
warning: implicitly-declared 'constexpr TokenRange::Iterator::Iterator(const TokenRange::Iterator&)'
is deprecated [-Wdeprecated-copy]
note: because 'TokenRange::Iterator' has user-provided
'TokenRange::Iterator& TokenRange::Iterator::operator=(const TokenRange::Iterator&)' | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
So this means, at some future point in time, the copy constructor will not be generated automatically anymore because you provided a custom assignment operator. So a possible fix is to just add a copy constructor as well.
Even better would be to not need to add copy and assignment operators, as at first glance it should not be necessary at all: the compiler should be able to automatically generate default functions that copy the std::string_views. The problem, as you found out yourself, is because of the const variables delimiters, stable_lexems and inword_symbols. Make them static instead.
About your final thoughts
It's great that you yourself realize that all this effort has made you learn a great deal, and that the code has improved because of it! You are also right about it being hard to get the iterator version correct, and it indeed requires quite a bit more code. Ideally, you would just want to write something as close as possible to the first revision, and still get the benefit of using it in a range-for loop. Since C++23 you can, by using std::generator<>. Your code would then look like:
std::generator<std::string_view> tokenize(std::string_view data) {
…
while (/* not done yet */) {
…
std::string_view token = …;
co_yield token;
…
}
} | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
I did not mention this before since this is a very recent addition to the language, and you thus also need a very recent compiler.
What should you use in your actual project? That's indeed up to you. Sometimes a quick and dirty hack is all you need. In larger projects, refactoring the code to make it more generic and more standards compliant will pay off though. If you don't know when to do what, consider applying the YAGNI principle.
When and how to decompose functions
There is this pervasive notion that more lines of code is bad. There is some truth to that: more lines means more possibilities of bugs, more to maintain, and more to document. However, the real problem is actually complex code. If you have one function of 100 lines of complex code, or ten simple functions of only 20 lines each, then despite the latter being 200 lines of code, it will actually have less chance of bugs, easier to maintain, and more self-documenting.
Of course, you should only decompose when it makes sense: if you can cleanly move some lines of code into a separate function, and that function then does something clear and simple (and thus can be given a clear and simple name), and it makes the original function less complex. Even skip_delimiters(), despite being just a few lines of code, is a great example of this.
It's hard to say what the right number of functions is, or what the maximum size of a function should be, that depends on the nature of the code of course. However, I can tell you that most people, including myself, don't decompose as much as they should.
The helper member functions you are creating should be private. They don't change the public API nor the ABI, so this is very safe to do. If you really want to avoid complicating your class declaration, you could consider instead to make them out-of-class functions, and then pass references to any member variables you want to modify. For example: | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
static void skip_delimiters(std::string_view& data, std::string_view delimiters) {
{
while (!data.empty() && std::ranges::contains(delimiters, data.front())) {
data.remove_prefix(1);
}
} | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, parsing
void TokenRange::Iterator::extract_lexem()
{
skip_delimiters(data, delimiters);
…
}
There might also be some other ways to approach this problem. | {
"domain": "codereview.stackexchange",
"id": 45493,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, parsing",
"url": null
} |
c++, multithreading, parsing
Title: Multithreaded natural language text parser
Question: Could you please conduct code review for the code below and suggest some improvements?
Functional specification
Implement a multithreading parser based on existing natural language tokenizer.
Parser should compile text into sequences of lexem ids.
Parser should create structures to get lexem text by id and id by lexem text.
Lexems id must be unique for lexem, but no any other stronger requirements are provided.
Parser should count how many times each lexem appeared in text. This functionality is nice to have and if removing it could dramatically simplify or speed up the parser, it could be ignored.
Performance and memory footprint is critical, since the amount of data is huge (gigabytes).
Nice to have the approach which could be portable to GPU for further speed up.
Design
The parser is based on the natural language text parser.
Being a proof of concept is utilizes the Microsoft concurrent_unordered_map which is not portable, but doesn’t require external libraries.
The project is expected to have some TextBases which hold lexems_data and dict maps to store lexems information to allow access trough lexem id and lexem text.
The proposed approach is to have two distinct types TextBaseSingleThreaded and TextBaseMultiThreaded to hold different types of maps, since std::maps is much faster in single-threaded execution.
The main piece of code is method TextBaseMultiThreaded::tokenize which splits the work in chunks and responsible for managing lexems on borders and merging the compiled sequences of lexem ids.
Reservations | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
Reservations
Please don’t consider the tokenizer code, since it is covered under the natural language text parser; feel free to participate there, if you like.
Another option would be to use OneAPI/tbb/concurrent_unordered_map to make the code portable, but this would require installing an additional library which I am in two minds about for proof of concept.
Most of types implemented as structs instead of classes to avoid swamping current code with getters and setters. Production code will utilize classes.
Don’t pay much attention to function main, except maybe usage of these objects from the client side.
I can’t find other multithreading parsers to learn from, so if you aware of such, please, share.
Key questions
The main question if the approach correct at all. First of all, it the idea of chunking the best one or something better (heaps?) could be used?
Is the object model correct or it could be improved? For example, I would like tokenizer to return CompiledText, but I don’t want to rely on RVO/NRVO which could frame me.
I am not sure if dynamic polymorphic types could help here.
Please review the tokenize and tokenize_chunk functions source code if it could/need to be improved and LexemDataAtomic structure.
One the long question about function extraction/decomposition, the tokenize (tokenize_chunk for multithreaded version) function here does two things, namely creating the dictionaries and compiling the text and this makes sense, since both are done simultaneously and we same execution time here. People often say that function must have one responsibility only. This works if the responsibilities could be split logically. Is there a chance to split these two responsibilities here without performance impact? Note, that data size expected to be huge, so even an additional pass could affect the performance.
What could be done better? | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
The source code
Fully functional runnable demo (requires Microsoft C++ compiler).
Please note that godbolt.org doesn’t run code with MSVC, so don’t expect to see the output.
Parser
using lexem_t = unsigned int;
struct LexemData {
lexem_t id;
std::size_t count;
};
struct LexemDataAtomic {
lexem_t id;
std::atomic<size_t> count;
LexemDataAtomic(unsigned int i, std::size_t count) :
id{ i },
count{ count }
{
}
LexemDataAtomic(const LexemDataAtomic& rhs) :
id{ rhs.id },
count{ rhs.count.load() }
{
}
LexemDataAtomic& operator=(const LexemDataAtomic& rhs)
{
if (&rhs != this)
{
id = rhs.id;
count = rhs.count.load();
}
}
LexemDataAtomic(LexemDataAtomic&&) = delete; // atomic is not moveable
LexemDataAtomic& operator=(LexemDataAtomic&&) = delete;
};
template <typename TextBaseType>
struct CompiledText {
TextBaseType& text_base;
std::vector<lexem_t> data;
CompiledText(TextBaseType& text_base) : text_base(text_base) {}
};
template <typename LexemsMapType, typename DictMapType>
struct TextBase {
LexemsMapType lexems_data;
DictMapType dict;
enum {
use_all_available_threads = 0,
};
};
struct TextBaseSingleThreaded
: public TextBase<std::unordered_map<std::string, LexemData>,
std::unordered_map<lexem_t, std::unordered_map<std::string, LexemData>::iterator>>
{
void tokenize(CompiledText<TextBaseSingleThreaded>& compiled_text, const std::string_view& text);
}; | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
struct TextBaseMultiThreaded
: public TextBase<Concurrency::concurrent_unordered_map<std::string, LexemDataAtomic>,
Concurrency::concurrent_unordered_map<lexem_t, Concurrency::concurrent_unordered_map<std::string, LexemDataAtomic>::iterator>>
{
void tokenize(CompiledText<TextBaseMultiThreaded>& compiled_text, const std::string_view& text, std::size_t threads = 0);
private:
void tokenize_chunk(std::vector<lexem_t>& compiled, TextBaseMultiThreaded& text_base, const std::string_view& text, lexem_t start_id);
};
void TextBaseSingleThreaded::tokenize(CompiledText<TextBaseSingleThreaded>& compiled_text, const std::string_view& text)
{
lexem_t id = 0;
for (auto lexem : TokenRange(text)) {
auto res = compiled_text.text_base.lexems_data.insert({ std::string(lexem), { id, 0 } });
if (res.second) {
compiled_text.text_base.dict[id] = res.first;
++id;
}
res.first->second.count++;
const int code = res.first->second.id;
compiled_text.data.push_back(code);
}
}
void TextBaseMultiThreaded::tokenize_chunk(std::vector<lexem_t>& compiled, TextBaseMultiThreaded& text_base, const std::string_view& text, lexem_t start_id)
{
auto id = start_id;
for (auto lexem : TokenRange(text)) {
auto res = text_base.lexems_data.insert({ std::string(lexem),{ id, 0} });
if (res.second) {
text_base.dict[id] = res.first;
++id;
}
++(res.first->second.count);
const int code = res.first->second.id;
compiled.push_back(code);
}
}
// If n_chunks == 0, use all available threads
void TextBaseMultiThreaded::tokenize(CompiledText<TextBaseMultiThreaded>& compiled_text, const std::string_view& text, std::size_t n_chunks)
{
n_chunks = n_chunks != use_all_available_threads ? n_chunks : std::max((std::size_t)std::thread::hardware_concurrency(), (std::size_t)1);
std::vector<std::thread> threads; | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
std::vector<std::thread> threads;
std::size_t chunk_size = text.size() / n_chunks;
std::vector<std::vector<lexem_t>> compiled(n_chunks);
std::size_t carry = 0;
const TokenRange empty({});
auto delimiters = empty.begin().get_delimiters();
for (std::size_t chunk = 0; chunk < n_chunks; ++chunk) {
if (carry >= chunk_size) {
carry -= chunk_size;
continue;
}
std::size_t chunk_start = chunk * chunk_size + carry;
std::size_t chunk_end = (chunk + 1) * chunk_size;
std::string_view search_range = text.substr(chunk_end - 1);
carry = search_range.find_first_of(delimiters);
if (std::string_view::npos == carry) {
carry = search_range.size();
}
chunk_end += carry;
auto text_for_chunk = text.substr(chunk_start, chunk_end - chunk_start);
threads.emplace_back(&TextBaseMultiThreaded::tokenize_chunk, this, std::ref(compiled[chunk]), std::ref(compiled_text.text_base),
text.substr(chunk_start, chunk_end - chunk_start), (lexem_t)(chunk * chunk_size));
}
for (auto& thread : threads) {
thread.join();
}
for (auto comp : compiled) {
compiled_text.data.insert(compiled_text.data.end(), comp.begin(), comp.end());
}
}
Function main
int main()
{
{
std::string sample = "Let's consider, this semi-simple sample, i.e. test data a+b with ints: 100, etc. For ... some testing...";
std::stringstream simply_parsed;
for (auto token : TokenRange(sample)) {
simply_parsed << token << " | ";
}
std::cout << "Simply parsed version: " << simply_parsed.str() << "\n";
TextBaseSingleThreaded single_threaded_text_base;
CompiledText<TextBaseSingleThreaded> single_threaded_compiled_text(single_threaded_text_base);
single_threaded_text_base.tokenize(single_threaded_compiled_text, sample); | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
single_threaded_text_base.tokenize(single_threaded_compiled_text, sample);
std::stringstream single_threaded;
for (std::size_t i = 0; i < single_threaded_compiled_text.data.size(); ++i) {
single_threaded << single_threaded_text_base.dict[single_threaded_compiled_text.data[i]]->first << " | ";
}
std::cout << "\nSingle-threaded version:" << single_threaded.str() << "\n";
TextBaseMultiThreaded multi_threaded_text_base;
CompiledText<TextBaseMultiThreaded> multi_threaded_compiled_text(multi_threaded_text_base);
multi_threaded_text_base.tokenize(multi_threaded_compiled_text, sample);
std::stringstream multi_threaded;
for (std::size_t i = 0; i < multi_threaded_compiled_text.data.size(); ++i) {
multi_threaded << multi_threaded_text_base.dict[multi_threaded_compiled_text.data[i]]->first << " | ";
}
std::cout << "\nMulti-threaded version:" << multi_threaded.str() << "\n\n";
std::cout << (simply_parsed.str() == single_threaded.str() ? "Single threaded test passed: OK" : "Single threaded test failed") << "\n";
std::cout << (simply_parsed.str() == multi_threaded.str() ? "Multi threaded test passed : OK" : "Multi threaded test failed") << "\n";
}
#define PERF
#ifdef PERF
{
std::cout << "\nPerformance testing:";
const std::size_t text_length = 100'000'00;
std::string text;
generate_text(text, text_length);
TextBaseSingleThreaded single_threaded_text_base;
CompiledText<TextBaseSingleThreaded> single_threaded_compiled_text(single_threaded_text_base);
TextBaseMultiThreaded multi_threaded_text_base;
CompiledText<TextBaseMultiThreaded> multi_threaded_compiled_text(multi_threaded_text_base);
{
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now(); | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
single_threaded_text_base.tokenize(single_threaded_compiled_text, text);
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
std::cout << "\nDuration of the single-threaded version = " << (std::chrono::duration<double>(now - start));
}
{
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
multi_threaded_text_base.tokenize(multi_threaded_compiled_text, text);
std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now();
std::cout << "\nDuration of the multi-threaded version = " << (std::chrono::duration<double>(now - start));
}
auto is_compiled_texts_equal = std::ranges::equal(single_threaded_compiled_text.data, multi_threaded_compiled_text.data, std::equal_to{},
[&](auto lex) {
return single_threaded_text_base.dict[lex]->first; },
[&](auto lex) {
return multi_threaded_text_base.dict[lex]->first; });
std::cout << "\n\n" << (is_compiled_texts_equal ? "Test passed: OK" : "Test failed") << "\n";
}
#endif //PERF
}
The expected results
On my PC (AMD Ryzen 9 3950X 16-Core Processor) it shows:
Simply parsed version: Let's | consider | , | <other text>
Single-threaded version: Let's | consider | , | <other text>
Multi-threaded version: Let's | consider | , | <other text>
Single threaded test passed: OK
Multi threaded test passed : OK
Performance testing:
Duration of the single-threaded version = 7.53919s
Duration of the multi-threaded version = 1.85347s
Test passed: OK | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
Test passed: OK
So, the performance improvement is more than 4 times.
An alternative approach
The alternative approach could be to use execution policies in parallel for_each. Less control over the cores usage, but manipulations with threads are hidden:
void TextBaseMultiThreaded::tokenize_with_for(CompiledText<TextBaseMultiThreaded>& compiled_text, const std::string_view& text)
{
std::size_t n_chunks = std::max((std::size_t)std::thread::hardware_concurrency(), (std::size_t)1);
std::size_t chunk_size = text.size() / n_chunks;
std::vector<std::vector<lexem_t>> compiled(n_chunks);
struct Info {
std::string_view text;
lexem_t start_id = 0;
};
std::vector<Info> info(n_chunks);
std::size_t carry = 0;
const TokenRange empty({});
auto delimiters = empty.begin().get_delimiters();
for (std::size_t chunk = 0; chunk < n_chunks; ++chunk) {
if (carry >= chunk_size) {
carry -= chunk_size;
continue;
}
std::size_t chunk_start = chunk * chunk_size + carry;
std::size_t chunk_end = (chunk + 1) * chunk_size;
std::string_view search_range = text.substr(chunk_end - 1);
carry = search_range.find_first_of(delimiters);
if (std::string_view::npos == carry) {
carry = search_range.size();
}
chunk_end += carry;
auto text_for_chunk = text.substr(chunk_start, chunk_end - chunk_start);
info[chunk].text = text.substr(chunk_start, chunk_end - chunk_start);
info[chunk].start_id = (lexem_t)(chunk * chunk_size);
}
std::for_each(std::execution::par_unseq, info.begin(), info.end(), [&](auto& item) {
std::size_t chunk = &item - info.data();
tokenize_chunk(compiled[chunk], compiled_text.text_base, item.text, item.start_id);
});
for (auto comp : compiled) {
compiled_text.data.insert(compiled_text.data.end(), comp.begin(), comp.end());
}
} | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
Answer: Answers to your questions
The main question if the approach correct at all. First of all, it the idea of chunking the best one or something better (heaps?) could be used?
It is a rather naive approach. There are several issues with it:
The total time depends on the slowest thread.
If you have more chunks than CPU cores, then you'll always have threads waiting for a timeslice. The OS has to perform context switching to make it seem they run concurrently, but this has an overhead.
If your chunks are too small, the overhead of spawning threads and having to merge the results of them at the end will dominate the total runtime.
Ideally, you have a thread pool that spawns only as many threads as there are CPU cores, and then have a queue of chunks that are not too small, and then each thread picks and processes chunks from the queue until it is empty.
Is the object model correct or it could be improved? For example, I would like tokenizer to return CompiledText, but I don’t want to rely on RVO/NRVO which could frame me.
RVO is guaranteed since C++17, but even before that many compilers would do that. I recommend you return a value instead of using an output parameter. See below for some possible benefits.
I am not sure if dynamic polymorphic types could help here.
I don't see any reason for it in your example code. I would avoid dynamic polymorphism unless you do have a good reason.
One the long question about function extraction/decomposition, the tokenize (tokenize_chunk for multithreaded version) function here does two things, namely creating the dictionaries and compiling the text […]. Is there a chance to split these two responsibilities here without performance impact?
I would start by writing the function in this way:
auto tokenize(…)
{
…
for (auto lexem: TokenRange(text)) {
add_to_dictionary(…, lexem);
add_to_data(…, lexem);
}
} | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
Now the responsibility of this function is just looping over the tokens and delegating further processing to two other functions.
Of course, now you might have to pass references to lots of things to those two new functions, which might clutter the code a bit. Still, each function now is much simpler. Also, the compiler will inline them so there should be no performance impact. The functions have names so the code is more self-documenting. I would consider this worth doing.
Avoid copying strings
Your LexemsMapType is always some kind of map from std::string to lexem data. But why not use std::string_view here as well? That avoids having to make actual copies of the strings.
Consider using std::async
If you are not going for the thread pool approach, then consider using std::async. This is like a thread, but it also captures the return value from the function, and automically joins (just like std::jthread). So combined with tokenize_chunk() returning the vector of lexems, you can write:
std::vector<std::future<std::vector<lexem_t>>> results;
results.reserve(n_chunks);
for (std::size_t chunk = 0; chunk < n_chunks; ++chunk) {
…
results.push_back(std::async(std::launch::async, tokenize_chunk(…)));
}
for (auto& result: results) {
compiled_text.data.append_range(result.get());
} | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
for (auto& result: results) {
compiled_text.data.append_range(result.get());
}
An added benefit of this approach is that it can already start processing the result of the first thread without having to wait for all the others to finish, although you can easily do that as well with your version by combining the last two for loops into one.
Pass std::string_views by value
A std::string_view is already kind of a reference type, and it's very small (just a pointer and a size). So passing a reference to a std::string_view is almost always unnecessary. I recommend passing them by value.
What performance improvement do you expect?
I already pointed out some possible performance issues caused by using multiple threads. In general, if you have \$N\$ threads, you will almost never get a speedup of a factor \$N\$, it's always going to be somewhat less, because virtually nothing will parallelize perfectly. Consider:
Starting and stopping threads has its own overhead.
You are doing a serial step after the multi-threaded part (combining the results into one std::vector). Even if the serial step is just a small fraction of the total work, it means the maximum speedup is a fixed number, regardless of how many threads you use (see Amdahl's law).
CPU processing power is not the only resource each thread consumes; memory bandwidth is another. If your tasks are doing a lot of memory reads and writes, memory will become the bottleneck.
Accessing shared resources is not free. Even accessing a std::atomic<int> is potentially much slower than a regular int. Your concurrent map might use a std::mutex under the hood to serialize access to the map.
So how much speedup do you expect to get from parallelizing your code? Now measure it with varying number of threads, and plot a graph showing the speedup you get. This will tell you if it's worth parallelizing, and after how many threads there will not be a gain anymore. | {
"domain": "codereview.stackexchange",
"id": 45494,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
python, python-3.x, calculator
Title: Mathematical calculation of engine fuel injectors
Question: There is a code that performs calculations of parts of fuel injectors. There are two classes in which the basic calculations take place, they are called LiquidJetInjector and GasJetInjector, respectively.
The Reynolds class stores constants for calculations.
The SimilarCalculations class is a class in which the calculations required in both LiquidJetInjector and GasJetInjector take place.
In order for the code to work correctly, first we need to pass the basic values to the SimilarCalculations class, and then to the class whose calculations we are interested in.
import math
from enum import Enum
class SimilarCalculations:
def __init__(self, diameter: float, length: float, mass_flow_rate: float, viscosity: float, density: float):
self.diameter = diameter
self.length = length
self.mass_flow_rate = mass_flow_rate
self.viscosity = viscosity
self.density = density
def injector_nozzle_area(self) -> float:
return (math.pi * self.diameter ** 2) / 4
def reynolds_number(self) -> float:
return (4 * self.mass_flow_rate) / (math.pi * self.diameter * self.viscosity)
def average_speed(self) -> float:
return self.mass_flow_rate / (self.density * self.injector_nozzle_area())
def relative_length_injector(self) -> float:
return self.length / self.diameter
class Reynolds(Enum):
LAMINAR = 2000
TURBULENT = 10000
class LiquidJetInjector:
def __init__(self, density_comb: float, sigma_fuel: float):
self.calculations = SimilarCalculations(diameter, length, mass_flow_rate, viscosity, density)
self.density_comb = density_comb
self.sigma_fuel = sigma_fuel
self.reynolds_number = self.calculations.reynolds_number()
self.injector_nozzle_area = self.calculations.injector_nozzle_area()
self.average_speed = self.calculations.average_speed() | {
"domain": "codereview.stackexchange",
"id": 45495,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, calculator",
"url": null
} |
python, python-3.x, calculator
def linear_hydraulic_resistance(self) -> float:
if self.reynolds_number < Reynolds.LAMINAR.value:
return 64 / self.reynolds_number
elif Reynolds.LAMINAR.value <= self.reynolds_number <= Reynolds.TURBULENT.value:
return 0.3164 * self.reynolds_number ** (-0.25)
else:
return 0.031
def injector_losses_inlet(self) -> float:
if self.reynolds_number < Reynolds.LAMINAR.value:
return 2.2 - 0.726 * math.exp(-74.5 * ((viscosity * length) / mass_flow_rate))
else:
return 1 + 2.65 * self.linear_hydraulic_resistance()
def injector_flow_coefficient(self) -> float:
return 1 / (math.sqrt(self.injector_losses_inlet() + self.linear_hydraulic_resistance() *
(length / diameter)))
def pressure_drop_injector(self) -> float:
return mass_flow_rate ** 2 / (2 * density * self.injector_flow_coefficient() ** 2 * self.injector_nozzle_area **
2)
def weber_criterion(self) -> float:
return (self.density_comb * self.average_speed ** 2 * diameter) / self.sigma_fuel
def media_diameter_spray_droplets(self) -> float:
return diameter * round(math.pow((27 * math.pi) / 4, 1 / 3.)) * self.weber_criterion() ** (-0.333)
class GasJetInjector:
def __init__(self, combustion_pressure: float, pressure_drop_internal_circuit: float, gas_constant_gen_gas: float,
temperature_gen_gas: float, entropy_expansion_ratio: float):
self.calculations = SimilarCalculations(diameter, length, mass_flow_rate, viscosity, density)
self.reynolds_number = self.calculations.reynolds_number()
self.injector_nozzle_area = self.calculations.injector_nozzle_area()
self.average_speed = self.calculations.average_speed() | {
"domain": "codereview.stackexchange",
"id": 45495,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, calculator",
"url": null
} |
python, python-3.x, calculator
self.combustion_pressure = combustion_pressure
self.pressure_drop_internal_circuit = pressure_drop_internal_circuit
self.gas_constant_gen_gas = gas_constant_gen_gas
self.temperature_gen_gas = temperature_gen_gas
self.entropy_expansion_ratio = entropy_expansion_ratio
def calculate_injector_pressure(self) -> float:
return self.combustion_pressure + self.pressure_drop_internal_circuit
def density_gen_gas(self) -> float:
return self.calculate_injector_pressure() / (self.gas_constant_gen_gas * self.temperature_gen_gas)
def injector_flow_coefficient(self) -> float:
return (math.sqrt(1.23 ** 2 + (232 * length) / (self.reynolds_number * diameter))) / \
((116 * length) / (self.reynolds_number * diameter))
def injector_nozzle_area_outlet(self) -> float:
return mass_flow_rate / (self.injector_flow_coefficient() * density * (
self.combustion_pressure / self.calculate_injector_pressure()) ** (1 / self.entropy_expansion_ratio) *
math.sqrt(2 * (self.entropy_expansion_ratio / (self.entropy_expansion_ratio - 1)) *
self.gas_constant_gen_gas * self.temperature_gen_gas * (1 - (
self.combustion_pressure / self.calculate_injector_pressure()) ** (
(self.entropy_expansion_ratio - 1) / self.entropy_expansion_ratio))))
def checking_diameter_injector(self) -> float:
return math.sqrt((4 * self.injector_nozzle_area_outlet()) / math.pi) | {
"domain": "codereview.stackexchange",
"id": 45495,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, calculator",
"url": null
} |
python, python-3.x, calculator
To test the values at the end of the code, I used this construction (it is temporary and will not be in the final version, but I will attach it to understand the work)
#
diameter = 0.0005
length = 0.002
mass_flow_rate = 0.00712
viscosity = 0.00116
density = 1315
#
density_comb = 0.1
sigma_fuel = 0.5
#
combustion_pressure = 14.58 * 10**6
pressure_drop_internal_circuit = 10**6
gas_constant_gen_gas = 260.5
temperature_gen_gas = 777.4
entropy_expansion_ratio = 1.23
#
calc = SimilarCalculations(diameter, length, mass_flow_rate, viscosity, density)
calc_2 = LiquidJetInjector(density_comb, sigma_fuel)
calc_3 = GasJetInjector(combustion_pressure, pressure_drop_internal_circuit, gas_constant_gen_gas, temperature_gen_gas, entropy_expansion_ratio)
#
print(calc_3.injector_nozzle_area_outlet())
print(calc_2.injector_flow_coefficient())
print(calc.injector_nozzle_area())
For a more accurate understanding of the formulas and parameters written in the code, I attach a link to the source of the manual according to which the code was written. The required pages are 38-44.
The manual for the calculation of liquid propellant injectors | {
"domain": "codereview.stackexchange",
"id": 45495,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, calculator",
"url": null
} |
python, python-3.x, calculator
Answer: SimilarCalculations is not a very good name. If we interpret it to be a superclass of your other two classes, it can simply be Injector. A superclass would be a simple and remove the need for a calculations member.
In your equations there's a lot of redundant parens, and not enough linebreaks. I'll demonstrate an alternative format that I find a little easier to understand.
Nearly all of your methods are simple and non-mutating. That's good! It means that they can be made @property.
Because your code is already non-mutating, you can tighten the class definition to a frozen dataclass.
You use math.pow in a place where the ** operator is simpler. Also, you write ** (-0.333) in the same line as raising to the power of 1 / 3.; the latter will be more accurate.
In your demo, you describe it as temporary - but it should be permanent! Convert it to unit tests.
Suggested
import math
from dataclasses import dataclass
from enum import Enum
@dataclass(frozen=True)
class Injector:
density: float
diameter: float
length: float
mass_flow_rate: float
viscosity: float
@property
def injector_nozzle_area(self) -> float:
return math.pi * self.diameter**2 / 4
@property
def reynolds_number(self) -> float:
return 4 * self.mass_flow_rate / (math.pi * self.diameter * self.viscosity)
@property
def average_speed(self) -> float:
return self.mass_flow_rate / (self.density * self.injector_nozzle_area)
@property
def relative_length_injector(self) -> float:
return self.length / self.diameter
class Reynolds(Enum):
LAMINAR = 2000
TURBULENT = 10000
@dataclass(frozen=True, slots=True)
class LiquidJetInjector(Injector):
density_comb: float
sigma_fuel: float | {
"domain": "codereview.stackexchange",
"id": 45495,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, calculator",
"url": null
} |
python, python-3.x, calculator
@property
def linear_hydraulic_resistance(self) -> float:
if self.reynolds_number < Reynolds.LAMINAR.value:
return 64 / self.reynolds_number
elif Reynolds.LAMINAR.value <= self.reynolds_number <= Reynolds.TURBULENT.value:
return 0.3164 * self.reynolds_number**-0.25
return 0.031
@property
def injector_losses_inlet(self) -> float:
if self.reynolds_number < Reynolds.LAMINAR.value:
return 2.2 - 0.726*math.exp(-74.5 * self.viscosity * self.length / self.mass_flow_rate)
return 1 + 2.65 * self.linear_hydraulic_resistance
@property
def injector_flow_coefficient(self) -> float:
return 1 / math.sqrt(
self.injector_losses_inlet
+ self.linear_hydraulic_resistance * self.length / self.diameter
)
@property
def pressure_drop_injector(self) -> float:
return self.mass_flow_rate**2 / (
2 * self.density * self.injector_flow_coefficient**2 *
self.injector_nozzle_area**2
)
@property
def weber_criterion(self) -> float:
return self.density_comb * self.average_speed**2 * self.diameter / self.sigma_fuel
@property
def media_diameter_spray_droplets(self) -> float:
return self.diameter * round(
(27 * math.pi / 4)**(1/3)
) * self.weber_criterion**(-1/3)
@dataclass(frozen=True, slots=True)
class GasJetInjector(Injector):
combustion_pressure: float
pressure_drop_internal_circuit: float
gas_constant_gen_gas: float
temperature_gen_gas: float
entropy_expansion_ratio: float
@property
def injector_pressure(self) -> float:
return self.combustion_pressure + self.pressure_drop_internal_circuit
@property
def density_gen_gas(self) -> float:
return self.injector_pressure / (self.gas_constant_gen_gas * self.temperature_gen_gas) | {
"domain": "codereview.stackexchange",
"id": 45495,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, calculator",
"url": null
} |
python, python-3.x, calculator
@property
def injector_flow_coefficient(self) -> float:
return math.sqrt(
1.23**2 + 232*self.length / (self.reynolds_number * self.diameter)
) / (116 * self.length) * self.reynolds_number * self.diameter
@property
def injector_nozzle_area_outlet(self) -> float:
return self.mass_flow_rate / (
self.injector_flow_coefficient * self.density * (
self.combustion_pressure / self.injector_pressure
) ** (1 / self.entropy_expansion_ratio) *
math.sqrt(
2 * self.entropy_expansion_ratio / (self.entropy_expansion_ratio - 1) *
self.gas_constant_gen_gas * self.temperature_gen_gas * (
1 - (
self.combustion_pressure / self.injector_pressure
) ** (
(self.entropy_expansion_ratio - 1) / self.entropy_expansion_ratio
)
)
)
)
@property
def checking_diameter_injector(self) -> float:
return math.sqrt(4 * self.injector_nozzle_area_outlet / math.pi)
def test() -> None:
common = {
'diameter': 0.0005,
'length': 0.002,
'mass_flow_rate': 0.00712,
'viscosity': 0.00116,
'density': 1315,
}
liquid = LiquidJetInjector(
**common, density_comb=0.1, sigma_fuel=0.5,
)
gas = GasJetInjector(
**common,
combustion_pressure=14.58e6,
pressure_drop_internal_circuit=1e6,
gas_constant_gen_gas=260.5,
temperature_gen_gas=777.4,
entropy_expansion_ratio=1.23,
)
assert math.isclose(gas.injector_nozzle_area_outlet, 8.279311695661635e-10)
assert math.isclose(gas.injector_nozzle_area, 1.9634954084936206e-07)
assert math.isclose(liquid.injector_flow_coefficient, 0.9105406506118756)
assert math.isclose(liquid.injector_nozzle_area, 1.9634954084936206e-07)
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 45495,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, calculator",
"url": null
} |
javascript, typescript, rxjs, browser-storage
Title: Efficient browser `StorageEvent` handling
Question: I have this class EfficientStorageEventProvider, which is responsible for efficient handling of StorageEvent
EfficientStorageEventProvider.ts
import { IStorageEventRecord } from "./IStorageEventRecord";
import { defer, Observable, share, Subject } from "rxjs";
import { doOnSubscriberCountChange } from "rx-do-on-subscriber-count-change";
import { isDefined, isUndefined } from "is-null";
/**
* {@link EfficientStorageEventProvider} is responsible for:
* - Efficient `"storage"` event handling
* (1 check if key is in map of observed keys per `StorageEvent`,
* instead of having `key_count` checks in every event listener
* if we should handle event with this key in current handler)
*/
export class EfficientStorageEventProvider {
private _observedKeyCount = 0;
private readonly _observedKeyToStorageEventRecordMap = new Map<
string,
IStorageEventRecord
>();
private readonly _handleStorageEvent: (storageEvent: StorageEvent) => void;
constructor() {
this._handleStorageEvent = (storageEvent: StorageEvent) => {
if (storageEvent.key !== null) {
const storageEventRecord = this._observedKeyToStorageEventRecordMap.get(
storageEvent.key,
);
if (isDefined(storageEventRecord)) {
storageEventRecord.storageEventS.next(storageEvent);
}
} else {
// If `key` is `null`, user requested to delete all items
this._observedKeyToStorageEventRecordMap.forEach(
(storageEventRecord2) => {
storageEventRecord2.storageEventS.next(storageEvent);
},
);
}
};
} | {
"domain": "codereview.stackexchange",
"id": 45496,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, rxjs, browser-storage",
"url": null
} |
javascript, typescript, rxjs, browser-storage
/**
* Notice that order of events is not guaranteed,
* and following from it, not all events may be processed at all!,
* because see https://stackoverflow.com/questions/77969202/in-which-order-storage-event-is-received
*/
getStorageEventForKey$(key: string): Observable<StorageEvent> {
return defer(() => {
let storageEventRecord =
this._observedKeyToStorageEventRecordMap.get(key);
if (isUndefined(storageEventRecord)) {
const storageEventS = new Subject<StorageEvent>();
const storageEvent$ = storageEventS.pipe(
doOnSubscriberCountChange((newSubscriberCount) => {
if (newSubscriberCount === 1) {
this._tryStartListeningStorageEvent();
} else if (newSubscriberCount === 0) {
this._observedKeyToStorageEventRecordMap.delete(key);
this._tryStopListeningStorageEvent();
}
}),
share(),
);
storageEventRecord = {
storageEvent$,
storageEventS,
};
this._observedKeyToStorageEventRecordMap.set(key, storageEventRecord);
}
return storageEventRecord.storageEvent$;
});
}
private _tryStartListeningStorageEvent() {
if (++this._observedKeyCount === 1) {
window.addEventListener("storage", this._handleStorageEvent);
}
}
private _tryStopListeningStorageEvent() {
if (--this._observedKeyCount === 0) {
window.removeEventListener("storage", this._handleStorageEvent);
}
}
}
doOnSubscriberCountChange.ts
import { Observable, OperatorFunction, Subscriber } from "rxjs";
export function doOnSubscriberCountChange<TValue>(
handleNewSubscriberCount: (newSubscriberCount: number) => void,
): OperatorFunction<TValue, TValue> {
return (source$) => {
let subscriberCount = 0; | {
"domain": "codereview.stackexchange",
"id": 45496,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, rxjs, browser-storage",
"url": null
} |
javascript, typescript, rxjs, browser-storage
return new Observable((subscriber: Subscriber<TValue>) => {
const subscription = source$.subscribe(subscriber);
handleNewSubscriberCount(++subscriberCount);
return () => {
subscription.unsubscribe();
handleNewSubscriberCount(--subscriberCount);
};
});
};
}
IStorageEventRecord.ts
import { Observable, Subject } from "rxjs";
export interface IStorageEventRecord {
storageEvent$: Observable<StorageEvent>;
storageEventS: Subject<StorageEvent>;
}
How can we improve it from point of view of performance/correctness/helpful-comments/more-representative-names?
Answer: rxjs has a steep learning curve, and it is difficult to explain to people how this code works or why it is correct.
Removing rxjs significantly eased understanding of this code, even by newer members of our team.
import { isDefined, isUndefined } from "is-null";
/**
* {@link EfficientStorageEventHandler} is responsible for:
* - Efficient `"storage"` event handling
* (1 check if key is in map of observed keys per `StorageEvent`
* and then calling correct handlers for key,
* instead of having `key_count` checks in every event listener
* if we should handle event with this key in current handler)
*/
export class EfficientStorageEventHandler {
private readonly _handleStorageEvent: (storageEvent: StorageEvent) => void;
private _observedKeyCount = 0;
private readonly _observedKeyToStorageEventHandlerSetMap = new Map<
string,
Set<(storageEvent: StorageEvent) => void>
>();
constructor() {
this._handleStorageEvent = (storageEvent: StorageEvent) => {
if (storageEvent.key !== null) {
const storageEventHandlerSet =
this._observedKeyToStorageEventHandlerSetMap.get(storageEvent.key); | {
"domain": "codereview.stackexchange",
"id": 45496,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, rxjs, browser-storage",
"url": null
} |
javascript, typescript, rxjs, browser-storage
if (isDefined(storageEventHandlerSet)) {
for (const storageEventHandler of storageEventHandlerSet) {
storageEventHandler(storageEvent);
}
}
} else {
// If `key` is `null`, user requested to delete all items
this._observedKeyToStorageEventHandlerSetMap.forEach(
(storageEventHandlerSet2) => {
for (const storageEventHandler of storageEventHandlerSet2) {
storageEventHandler(storageEvent);
}
},
);
}
};
}
/**
* Notice that order of events is not guaranteed,
* and following from it, not all events may be processed at all!,
* because see https://stackoverflow.com/questions/77969202/in-which-order-storage-event-is-received
*
* @return function which will stop listening `storageEventHandler`
* when called
*/
addStorageEventHandler(
key: string,
storageEventHandler: (storageEvent: StorageEvent) => void,
): () => void {
let storageEventHandlerSet =
this._observedKeyToStorageEventHandlerSetMap.get(key);
if (isUndefined(storageEventHandlerSet)) {
this._tryStartListeningStorageEvent();
storageEventHandlerSet = new Set<(storageEvent: StorageEvent) => void>([
storageEventHandler,
]);
this._observedKeyToStorageEventHandlerSetMap.set(
key,
storageEventHandlerSet,
);
} else {
storageEventHandlerSet.add(storageEventHandler);
}
// Making `storageEventHandlerSet2` `const` to tell compiler that
// `storageEventHandlerSet2` can't change and is always defined
const storageEventHandlerSet2 = storageEventHandlerSet;
return () => {
storageEventHandlerSet2.delete(storageEventHandler);
if (storageEventHandlerSet2.size === 0) {
this._observedKeyToStorageEventHandlerSetMap.delete(key);
this._tryStopListeningStorageEvent();
}
};
} | {
"domain": "codereview.stackexchange",
"id": 45496,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, rxjs, browser-storage",
"url": null
} |
javascript, typescript, rxjs, browser-storage
private _tryStartListeningStorageEvent() {
if (++this._observedKeyCount === 1) {
window.addEventListener("storage", this._handleStorageEvent);
}
}
private _tryStopListeningStorageEvent() {
if (--this._observedKeyCount === 0) {
window.removeEventListener("storage", this._handleStorageEvent);
}
}
}
If we need to combine it with rxjs, we can use code like
const efficientStorageEventHandler = new EfficientStorageEventHandler();
const key = 'someKey'
const efficientStorageEvent$ = new Observable<StorageEvent>((subscriber) => {
const unsubscribe = efficientStorageEventHandler.addStorageEventHandler(
key,
(storageEvent) => {
subscriber.next(storageEvent);
},
);
return unsubscribe;
}); | {
"domain": "codereview.stackexchange",
"id": 45496,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, rxjs, browser-storage",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Title: recursive_invocable and recursive_project_invocable Concept Implementation in C++
Question: This is a follow-up question for A recursive_find_if Template Function with Unwrap Level Implementation in C++. I am trying to make some constrains on Proj and UnaryPredicate in recursive_all_of, recursive_find_if, recursive_any_of and recursive_none_of template functions. The recursive_invocable concept specifies that a callable type F can be called with unwrapped arguments T....
recursive_invocable Concept Implementation
// is_recursive_invocable template function implementation
template<std::size_t unwrap_level, class F, class... T>
requires(unwrap_level <= recursive_depth<T...>())
static constexpr bool is_recursive_invocable()
{
if constexpr (unwrap_level == 0) {
if constexpr (std::invocable<F, T...>)
return true;
else
return false;
} else if constexpr (unwrap_level > 0) {
return is_recursive_invocable<
unwrap_level - 1,
F,
std::ranges::range_value_t<T>...>();
} else {
return false;
}
}
// recursive_invocable concept
template<std::size_t unwrap_level, class F, class... T>
concept recursive_invocable =
is_recursive_invocable<unwrap_level, F, T...>(); | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
recursive_project_invocable Concept Implementation
// is_recursive_project_invocable template function implementation
template<std::size_t unwrap_level, class Proj, class F, class... T>
requires(unwrap_level <= recursive_depth<T...>() &&
recursive_invocable<unwrap_level, Proj, T...>)
static constexpr bool is_recursive_project_invocable()
{
if constexpr (unwrap_level == 0) {
if constexpr (std::invocable<F, std::invoke_result_t<Proj, T...>>)
return true;
else
return false;
} else if constexpr (unwrap_level > 0) {
return is_recursive_project_invocable<
unwrap_level - 1,
Proj,
F,
std::ranges::range_value_t<T>...>();
} else {
return false;
}
}
// recursive_project_invocable concept
template<std::size_t unwrap_level, class Proj, class F, class... T>
concept recursive_project_invocable =
is_recursive_project_invocable<unwrap_level, Proj, F, T...>();
Full Testing Code
The full testing code:
// recursive_invocable and recursive_project_invocable Concept Implementation in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
//#include <experimental/ranges/algorithm>
#include <experimental/array>
#include <functional>
#include <iostream>
#include <iterator>
#include <ranges>
#include <string>
#include <utility>
#include <vector>
// is_reservable concept
template<class T>
concept is_reservable = requires(T input)
{
input.reserve(1);
};
// is_sized concept, https://codereview.stackexchange.com/a/283581/231235
template<class T>
concept is_sized = requires(T x)
{
std::size(x);
};
template<typename T>
concept is_summable = requires(T x) { x + x; };
// recursive_unwrap_type_t struct implementation
template<std::size_t, typename, typename...>
struct recursive_unwrap_type { }; | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...>
{
using type = std::ranges::range_value_t<Container1<Ts1...>>;
};
template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...>
{
using type = typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>
>::type;
};
template<std::size_t unwrap_level, typename T1, typename... Ts>
using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type;
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
};
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
// recursive_array_invoke_result implementation
template<std::size_t, typename, typename, typename...>
struct recursive_array_invoke_result { };
template< typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
struct recursive_array_invoke_result<1, F, Container<T, N>>
{
using type = Container<
std::invoke_result_t<F, std::ranges::range_value_t<Container<T, N>>>,
N>;
}; | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template< std::size_t unwrap_level,
typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires ( std::ranges::input_range<Container<T, N>> &&
requires { typename recursive_array_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges
struct recursive_array_invoke_result<unwrap_level, F, Container<T, N>>
{
using type = Container<
typename recursive_array_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container<T, N>>
>::type, N>;
};
template< std::size_t unwrap_level,
typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
using recursive_array_invoke_result_t = typename recursive_array_invoke_result<unwrap_level, F, Container<T, N>>::type;
// recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035
template<std::size_t, typename>
struct recursive_array_unwrap_type { };
template<template<class, std::size_t> class Container,
typename T,
std::size_t N>
struct recursive_array_unwrap_type<1, Container<T, N>>
{
using type = std::ranges::range_value_t<Container<T, N>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<std::size_t unwrap_level, template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires ( std::ranges::input_range<Container<T, N>> &&
requires { typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges
struct recursive_array_unwrap_type<unwrap_level, Container<T, N>>
{
using type = typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>
>::type;
};
template<std::size_t unwrap_level, class Container>
using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type;
// https://codereview.stackexchange.com/a/253039/231235
template<std::size_t dim, class T, template<class...> class Container = std::vector>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, T, Container>(input, times));
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output;
for (size_t i = 0; i < times; i++)
{
output[i] = n_dim_array_generator<dim - 1, times>(input);
}
return output;
}
}
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1};
} | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_depth function implementation with target type
template<typename T_Base, typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<typename T_Base, std::ranges::input_range Range>
requires (!std::same_as<Range, T_Base>)
constexpr std::size_t recursive_depth()
{
return recursive_depth<T_Base, std::ranges::range_value_t<Range>>() + std::size_t{1};
}
// is_recursive_invocable template function implementation
template<std::size_t unwrap_level, class F, class... T>
requires(unwrap_level <= recursive_depth<T...>())
static constexpr bool is_recursive_invocable()
{
if constexpr (unwrap_level == 0) {
if constexpr (std::invocable<F, T...>)
return true;
else
return false;
} else if constexpr (unwrap_level > 0) {
return is_recursive_invocable<
unwrap_level - 1,
F,
std::ranges::range_value_t<T>...>();
} else {
return false;
}
}
// recursive_invocable concept
template<std::size_t unwrap_level, class F, class... T>
concept recursive_invocable =
is_recursive_invocable<unwrap_level, F, T...>();
// is_recursive_project_invocable template function implementation
template<std::size_t unwrap_level, class Proj, class F, class... T>
requires(unwrap_level <= recursive_depth<T...>() &&
recursive_invocable<unwrap_level, Proj, T...>)
static constexpr bool is_recursive_project_invocable()
{
if constexpr (unwrap_level == 0) {
if constexpr (std::invocable<F, std::invoke_result_t<Proj, T...>>)
return true;
else
return false;
} else if constexpr (unwrap_level > 0) {
return is_recursive_project_invocable<
unwrap_level - 1,
Proj,
F,
std::ranges::range_value_t<T>...>();
} else {
return false;
}
} | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_project_invocable concept
template<std::size_t unwrap_level, class Proj, class F, class... T>
concept recursive_project_invocable =
is_recursive_project_invocable<unwrap_level, Proj, F, T...>();
/* recursive_all_of template function implementation with unwrap level
*/
template<std::size_t unwrap_level, class T, class Proj = std::identity, class UnaryPredicate>
requires( unwrap_level <= recursive_depth<T>() &&
recursive_invocable<unwrap_level, Proj, T> &&
recursive_project_invocable<unwrap_level, Proj, UnaryPredicate, T>)
constexpr auto recursive_all_of(T&& value, UnaryPredicate&& p, Proj&& proj = {}) {
if constexpr (unwrap_level > 0)
{
return std::ranges::all_of(value, [&](auto&& element) {
return recursive_all_of<unwrap_level - 1>(element, p, proj);
});
}
else
{
return std::invoke(p, std::invoke(proj, value));
}
}
/* recursive_find_if template function implementation with unwrap level
*/
template<std::size_t unwrap_level, class T, class Proj = std::identity, class UnaryPredicate>
requires( unwrap_level <= recursive_depth<T>() &&
recursive_invocable<unwrap_level, Proj, T> &&
recursive_project_invocable<unwrap_level, Proj, UnaryPredicate, T>)
constexpr auto recursive_find_if(T&& value, UnaryPredicate&& p, Proj&& proj = {}) {
if constexpr (unwrap_level > 0)
{
return std::ranges::find_if(value, [&](auto& element) {
return recursive_find_if<unwrap_level - 1>(element, p, proj);
}) != std::ranges::end(value);
}
else
{
return std::invoke(p, std::invoke(proj, value));
}
} | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_any_of template function implementation with unwrap level
template<std::size_t unwrap_level, class T, class Proj = std::identity, class UnaryPredicate>
requires( unwrap_level <= recursive_depth<T>() &&
recursive_invocable<unwrap_level, Proj, T> &&
recursive_project_invocable<unwrap_level, Proj, UnaryPredicate, T>)
constexpr auto recursive_any_of(T&& value, UnaryPredicate&& p, Proj&& proj = {})
{
return recursive_find_if<unwrap_level>(value, p, proj);
}
// recursive_none_of template function implementation with unwrap level
template<std::size_t unwrap_level, class T, class Proj = std::identity, class UnaryPredicate>
requires( unwrap_level <= recursive_depth<T>() &&
recursive_invocable<unwrap_level, Proj, T> &&
recursive_project_invocable<unwrap_level, Proj, UnaryPredicate, T>)
constexpr auto recursive_none_of(T&& value, UnaryPredicate&& p, Proj&& proj = {})
{
return !recursive_any_of<unwrap_level>(value, p, proj);
}
template<std::ranges::input_range T>
constexpr auto recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<std::ranges::input_range T>
requires (std::ranges::input_range<std::ranges::range_value_t<T>>)
constexpr T recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
void recursive_find_if_tests()
{
auto test_vectors_1 = n_dim_container_generator<4, int, std::vector>(1, 3);
test_vectors_1[0][0][0][0] = 2;
assert(recursive_find_if<4>(test_vectors_1, [](auto&& i) { return i % 2 == 0; }));
auto test_vectors_2 = n_dim_container_generator<4, int, std::vector>(3, 3);
assert(recursive_find_if<4>(test_vectors_2, [](auto&& i) { return i % 2 == 0; }) == false);
// Tests with std::string
auto test_vector_string = n_dim_container_generator<4, std::string, std::vector>("1", 3);
assert(recursive_find_if<4>(test_vector_string, [](auto&& i) { return i == "1"; }));
assert(recursive_find_if<4>(test_vector_string, [](auto&& i) { return i == "2"; }) == false);
// Tests with std::string, projection
assert(recursive_find_if<4>(
test_vector_string,
[](auto&& i) { return i == "1"; },
[](auto&& element) {return std::to_string(std::stoi(element) + 1); }) == false);
assert(recursive_find_if<4>(
test_vector_string,
[](auto&& i) { return i == "2"; },
[](auto&& element) {return std::to_string(std::stoi(element) + 1); }));
// Tests with std::array of std::string
std::array<std::string, 3> word_array1 = {"foo", "foo", "foo"};
assert(recursive_find_if<1>(word_array1, [](auto&& i) { return i == "foo"; }));
assert(recursive_find_if<1>(word_array1, [](auto&& i) { return i == "bar"; }) == false); | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// Tests with std::deque of std::string
std::deque<std::string> word_deque1 = {"foo", "foo", "foo", "bar"};
assert(recursive_find_if<1>(word_deque1, [](auto&& i) { return i == "foo"; }));
assert(recursive_find_if<1>(word_deque1, [](auto&& i) { return i == "bar"; }));
assert(recursive_find_if<1>(word_deque1, [](auto&& i) { return i == "abcd"; }) == false);
assert(recursive_find_if<2>(word_deque1, [](auto&& i) { return i == 'a'; }));
assert(recursive_find_if<2>(word_deque1, [](auto&& i) { return i == 'b'; }));
assert(recursive_find_if<2>(word_deque1, [](auto&& i) { return i == 'c'; }) == false);
std::vector<std::wstring> wstring_vector1{};
for(int i = 0; i < 4; ++i)
{
wstring_vector1.push_back(std::to_wstring(1));
}
assert(recursive_find_if<1>(wstring_vector1, [](auto&& i) { return i == std::to_wstring(1); }));
assert(recursive_find_if<1>(wstring_vector1, [](auto&& i) { return i == std::to_wstring(2); }) == false);
std::vector<std::u8string> u8string_vector1{};
for(int i = 0; i < 4; ++i)
{
u8string_vector1.push_back(u8"\u20AC2.00");
}
assert(recursive_find_if<1>(u8string_vector1, [](auto&& i) { return i == u8"\u20AC2.00"; }));
assert(recursive_find_if<1>(u8string_vector1, [](auto&& i) { return i == u8"\u20AC1.00"; }) == false);
std::pmr::string pmr_string1 = "123";
std::vector<std::pmr::string> pmr_string_vector1 = {pmr_string1, pmr_string1, pmr_string1};
assert(recursive_find_if<1>(pmr_string_vector1, [](auto&& i) { return i == "123"; }));
assert(recursive_find_if<1>(pmr_string_vector1, [](auto&& i) { return i == "456"; }) == false);
std::cout << "All tests passed!\n";
return;
}
void recursive_any_of_tests()
{
auto test_vectors_1 = n_dim_container_generator<4, int, std::vector>(1, 3);
test_vectors_1[0][0][0][0] = 2;
assert(recursive_any_of<4>(test_vectors_1, [](auto&& i) { return i % 2 == 0; })); | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
auto test_vectors_2 = n_dim_container_generator<4, int, std::vector>(3, 3);
assert(recursive_any_of<4>(test_vectors_2, [](auto&& i) { return i % 2 == 0; }) == false);
// Tests with std::string
auto test_vector_string = n_dim_container_generator<4, std::string, std::vector>("1", 3);
assert(recursive_any_of<4>(test_vector_string, [](auto&& i) { return i == "1"; }));
assert(recursive_any_of<4>(test_vector_string, [](auto&& i) { return i == "2"; }) == false);
// Tests with std::string, projection
assert(recursive_any_of<4>(
test_vector_string,
[](auto&& i) { return i == "1"; },
[](auto&& element) {return std::to_string(std::stoi(element) + 1); }) == false);
assert(recursive_any_of<4>(
test_vector_string,
[](auto&& i) { return i == "2"; },
[](auto&& element) {return std::to_string(std::stoi(element) + 1); }));
// Tests with std::array of std::string
std::array<std::string, 3> word_array1 = {"foo", "foo", "foo"};
assert(recursive_any_of<1>(word_array1, [](auto&& i) { return i == "foo"; }));
assert(recursive_any_of<1>(word_array1, [](auto&& i) { return i == "bar"; }) == false);
// Tests with std::deque of std::string
std::deque<std::string> word_deque1 = {"foo", "foo", "foo", "bar"};
assert(recursive_any_of<1>(word_deque1, [](auto&& i) { return i == "foo"; }));
assert(recursive_any_of<1>(word_deque1, [](auto&& i) { return i == "bar"; }));
assert(recursive_any_of<1>(word_deque1, [](auto&& i) { return i == "abcd"; }) == false);
assert(recursive_any_of<2>(word_deque1, [](auto&& i) { return i == 'a'; }));
assert(recursive_any_of<2>(word_deque1, [](auto&& i) { return i == 'b'; }));
assert(recursive_any_of<2>(word_deque1, [](auto&& i) { return i == 'c'; }) == false); | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::vector<std::wstring> wstring_vector1{};
for(int i = 0; i < 4; ++i)
{
wstring_vector1.push_back(std::to_wstring(1));
}
assert(recursive_any_of<1>(wstring_vector1, [](auto&& i) { return i == std::to_wstring(1); }));
assert(recursive_any_of<1>(wstring_vector1, [](auto&& i) { return i == std::to_wstring(2); }) == false);
std::vector<std::u8string> u8string_vector1{};
for(int i = 0; i < 4; ++i)
{
u8string_vector1.push_back(u8"\u20AC2.00");
}
assert(recursive_any_of<1>(u8string_vector1, [](auto&& i) { return i == u8"\u20AC2.00"; }));
assert(recursive_any_of<1>(u8string_vector1, [](auto&& i) { return i == u8"\u20AC1.00"; }) == false);
std::pmr::string pmr_string1 = "123";
std::vector<std::pmr::string> pmr_string_vector1 = {pmr_string1, pmr_string1, pmr_string1};
assert(recursive_any_of<1>(pmr_string_vector1, [](auto&& i) { return i == "123"; }));
assert(recursive_any_of<1>(pmr_string_vector1, [](auto&& i) { return i == "456"; }) == false);
std::cout << "All tests passed!\n";
return;
}
int main()
{
auto start = std::chrono::system_clock::now();
recursive_find_if_tests();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n';
return EXIT_SUCCESS;
}
The output of the test code above:
All tests passed!
Computation finished at Wed Feb 14 04:17:35 2024
elapsed time: 5.9873e-05
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_find_if Template Function with Unwrap Level Implementation in C++ | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
What changes has been made in the code since last question?
I am trying to implement recursive_invocable and recursive_project_invocable concepts for recursive_all_of, recursive_find_if, recursive_any_of and recursive_none_of template functions in this post.
Why a new review is being asked for?
Please review the implementation of recursive_invocable and recursive_project_invocable concepts. Is the constraint designed properly? All suggestions are welcome.
Answer: Your code is correct, however it can be simplified in a number of ways:
Unnecessary if-statements
Whenever you see if (foo) return true; else return false;, you can replace that by return foo.
Next, consider that unwrap_level is an unsigned integer, and you already checked the case where it is zero or where it is greater than zero. The last else-branch is therefore useless.
So your code in is_recursive_invocable() can be replaced with:
if constexpr (unwrap_level == 0) {
return std::invocable<F, T...>;
} else {
return is_recursive_invocable<unwrap_level - 1, F,
std::ranges::range_value_t<T>...>();
}
About is_recursive_project_invocable()
Note that in the standard library, there is no concept named projected_invocable(). Instead, functions like std::ranges::find_if() check for something like std::invocable<F, std::invoke_result_t<Proj, T...>> instead. You already have a way to get the recursive invoke result, so you could write:
template<class F, std::size_t unwrap_level, class Proj, class... T>
concept recursive_projected_invocable =
std::invocable<F, recursive_variadic_invoke_result_t<unwrap_level, Proj, T...>>; | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Note that I moved the template parameter F to the front (which could also be done for recursive_invocable). This allows you to use this concept as shown below:
Remove redundant constraints
Your recursive_find_if() function checks for three things in its requires-clause. However, the first two are redundant; recursive_project_invocable alone is enough to validate that the unwrap_level is correct, that Proj is valid at that level, and that the result of that can be used by the predicate. So, you can simplify it to:
template<std::size_t unwrap_level, class T, class Proj = std::identity,
recursive_projected_invocable<unwrap_level, Proj, T> UnaryPredicate>
constexpr auto recursive_find_if(T&& value, UnaryPredicate&& p, Proj&& proj = {}) {
…
} | {
"domain": "codereview.stackexchange",
"id": 45497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, recursion, template, c++20, constrained-templates",
"url": null
} |
python, api, fastapi
Title: FastAPI repository endpoint for version control system
Question: I am creating an API for a version control system. This is my first time creating an API (and a web project in general) and I wanted to get some feedback. I plan to connect this API to a frontend to create website. I choose to share this part of the code because the rest of the code follows this structure. For reference: Users have repositories ; repositories have commits, files and branches; branches point to a specific commit; commits and files have a many to many relationship.
router = APIRouter(prefix= "/{user_name}", tags=["repository"])
@router.post("/", response_model= schemas.RepositoryResponseSchema ,status_code=status.HTTP_201_CREATED)
def create_repo(user_name: str, repo_name : str,
db: Session = Depends(database.get_db), current_user = Depends(oauth2.get_current_user)):
if current_user.name != user_name:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User does not have permission to create a repository for another user")
user = crud.get_one_or_error(db, models.User, name= user_name)
repo = crud.create_unique_or_error(db, models.Repository, name= repo_name, creator= user)
master_branch = crud.create_unique_or_error(db, models.Branch, name= "master", head_commit_oid = None, repository_id= repo.id)
repo.branches.append(master_branch)
repo.current_branch_id = master_branch.id
db.commit()
return repo | {
"domain": "codereview.stackexchange",
"id": 45498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, api, fastapi",
"url": null
} |
python, api, fastapi
@router.put("/{repository_name}/change-branch", response_model=schemas.ChangeBranchResponse, status_code=status.HTTP_200_OK)
def change_branch(user_name: str, repository_name: str, branch_name: str,
db: Session = Depends(database.get_db), current_user = Depends(oauth2.get_current_user)):
if current_user.name != user_name:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User does not have permission to change a branch for another user")
user = crud.get_one_or_error(db, models.User, name= user_name)
repo = crud.get_one_or_error(db, models.Repository, name= repository_name, creator= user)
branch = crud.get_one_or_error(db, models.Branch, name= branch_name, repository_id= repo.id)
repo.current_branch = branch
db.commit()
return schemas.ChangeBranchResponse(repo.name, branch_name=branch.name)
@router.get("/{repository_name}/tree", status_code=status.HTTP_200_OK)
def get_tree_for_repo(user_name: str, repository_name: str, db: Session = Depends(database.get_db)):
"""Return the graph formed by commits and branches
o → o → o → o → o → o
↓ ↑
o ← dev_branch master_branch
"""
user = crud.get_one_or_error(db, models.User, name= user_name)
repo = crud.get_one_or_error(db, models.Repository, name= repository_name, creator_id= user.id)
# Create an empty directed graph
graph = nx.DiGraph()
for branch in repo.branches:
head = branch.head_commit_oid
commit = crud.get_one_or_error(db, models.Commit, oid=head, repository_id= repo.id)
while commit:
graph.add_node(commit.oid, label=f"Commit: {commit.commit_message}")
if commit.parent_oid:
graph.add_edge(commit.parent_oid, commit.oid)
else:
root = commit.oid # Returnning this could be good for drawing better graphs | {
"domain": "codereview.stackexchange",
"id": 45498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, api, fastapi",
"url": null
} |
python, api, fastapi
commit = crud.get_one_or_none(db, models.Commit, oid=commit.parent_oid, repository_id= repo.id)
return json_graph.node_link_data(graph)
I am unsure with some of my design choices and I am looking for some feedback.
Answer: design of URL namespace
@router.post("/", ... )
def create_repo( ...
This seems like the wrong URI.
Prefer "/{repository_name}".
As stated it seems like we're creating a user.
Also, "lint": prefer
$ black *.py
over the idiosyncratic spacing choices found in OP.
boilerplate
We naturally see these a fair amount in signatures:
def ...
db: Session = Depends(database.get_db),
current_user = Depends(oauth2.get_current_user)):
if current_user.name != user_name:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="... permission ...")
Could an @authenticated decorator maybe subsume them?
Import nit: It might be convenient to add aliases like
from status import HTTP_403_FORBIDDEN
conventional branch name
master_branch = crud.create_unique_or_error( ... , name= "master", ... )
There are good reasons why GitHub and others
have long ago ditched that name, in favor of main.
You might choose similar defaulting.
insert
repo = crud.create_unique_or_error( ...
repo.branches.append(master_branch)
You chose to omit imports and a lot of other essential Review Context.
For example, each import is implicitly a pypi docu-pointer.
Here, I do not know what that last line did.
My fear is that the ORM has a list that we tacked the branch onto,
and the DB table has a JSON column containing a list or something
like that.
In other words, that the DB is de-normed.
I encourage you to
normalize,
to INSERT a separate row for each and every branch.
Later on you'll be glad that you did.
Avoid aggregates such as "list" or "array" columns,
as they make relational queries harder, and harder to optimize.
backend vs UI
def change_branch( ... | {
"domain": "codereview.stackexchange",
"id": 45498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, api, fastapi",
"url": null
} |
python, api, fastapi
This is a mapping from "(user, repo)" to "default branch".
It's not obvious to me that the backend has to offer
such a service at all.
It feels more like a frontend UI kind of thing.
And it seems like the UI might have multiple preference settings
to keep track of, beyond just "current branch".
Suppose I merge a pair of branches, big enough that conflict resolution
takes more than a second. Meanwhile I do some other operation
on another branch. Do I need to worry about racing default branch name?
I would expect that each operation would explicitly mention
things like (user, repo, branch), rather than letting branch
default to the current one. The UI does such defaulting, sure,
but not sending explicit branch name to the backend API seems a bit off.
Instead of a branch name,
maybe operations like merge send an unnamed hash to the backend?
more boilerplate
@router.get("/{repository_name}/tree", status_code=status.HTTP_200_OK)
We will want to default that 200, right?
Possibly with a decorator, or with a souped-up router object.
scaling
def get_tree_for_repo( ...
graph = nx.DiGraph()
for branch in repo.branches:
head = branch.head_commit_oid
commit = crud.get_one_or_error( ... )
while commit:
graph.add_node( ... ) | {
"domain": "codereview.stackexchange",
"id": 45498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, api, fastapi",
"url": null
} |
python, api, fastapi
For a "hello world" repo I'm sure that's very nice.
You will want to test against realworld historic repos with
a few years of commits in them.
Not linux kernel, but maybe from say an Apache project,
something biggish.
You will soon discover that users will wish to
limit their exploration of the graph to a certain
date range, or the last K commits resulting in a certain tag ID.
Else traversing the graph will take all day.
Your design should bear in mind that some queries
will want to quickly chase digraph arrows in the "opposite" direction.
Also, when reporting on a giant graph,
the crud.get_one_... is insanity.
I'm looking at N roundtrips to the DB for N commits.
Figure out how to issue a single giant SELECT ... WHERE ...
so the database backend planner knows you want everything.
It will find an appropriate access path,
gather up the result rows, and stream them at you
as fast as TCP can go, rather than doing a stutter stop
next row next row for each of N rows.
documentation
It's unclear what the various concepts in your VC system are.
So document them, and include URL of documentation in your source code.
Hard way would be to document from scratch.
Easier way would be to stand on the shoulders of giant Linus,
who in turns stands on the shoulders of others.
Write down that your system is "just like git",
or more likely that it is "git lite" and then delineate the limits. | {
"domain": "codereview.stackexchange",
"id": 45498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, api, fastapi",
"url": null
} |
python, performance, beginner
Title: Making an "analogue display" by drawing boxes
Question: This is a personal (very amateur) project to teach myself how to use if statements, lists/tuples, loops, etc. It takes an input of one letter and using a pygame-based module drawly written by one of my university professors, it draws that letter using numbered boxes (essentially pixels) that "turn on and off" based on their inclusion in box_list.
letter = input("What should we draw? (Your options are letters A-Z and punctuation marks "
". and ?) ")
drawly.start(letter, (170, 370), "aliceblue")
box_list = []
if letter in ("A", "a"):
drawly.set_color("red")
box_list = [2, 4, 6, 7, 9, 10, 11, 12, 13, 15, 16, 18, 19, 21]
if letter in ("B", "b"):
drawly.set_color("green3")
box_list = [1, 2, 4, 6, 7, 9, 10, 11, 13, 15, 16, 18, 19, 20]
if letter in ("C", "c"):
drawly.set_color("darkgoldenrod1")
box_list = [2, 3, 4, 7, 10, 13, 16, 20, 21]
if letter in ("D", "d"):
drawly.set_color("blue")
box_list = [1, 2, 4, 6, 7, 9, 10, 12, 13, 15, 16, 18, 19, 20]
if letter in ("E", "e"):
box_list = [1, 2, 3, 4, 7, 10, 11, 13, 16, 19, 20, 21]
if letter in ("F", "f"):
box_list = [1, 2, 3, 4, 7, 10, 11, 13, 16, 19]
if letter in ("G", "g"):
box_list = [2, 3, 4, 7, 10, 12, 13, 15, 16, 18, 19, 20]
if letter in ("H", "h"):
box_list = [1, 3, 4, 6, 7, 9, 10, 11, 12, 13, 15, 16, 18, 19, 21]
if letter in ("I", "i"):
box_list = [1, 2, 3, 5, 8, 11, 14, 17, 19, 20, 21]
if letter in ("J", "j"):
box_list = [3, 6, 9, 12, 15, 16, 18, 20]
if letter in ("K", "k"):
box_list = [1, 3, 4, 6, 7, 9, 10, 11, 13, 15, 16, 18, 19, 21]
if letter in ("L", "l"):
box_list = [1, 4, 7, 10, 13, 16, 19, 20, 21]
if letter in ("M", "m"):
box_list = [1, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 16, 18, 19, 21]
if letter in ("N", "n"):
box_list = [1, 2, 4, 6, 7, 9, 10, 12, 13, 15, 16, 18, 19, 21] | {
"domain": "codereview.stackexchange",
"id": 45499,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner",
"url": null
} |
python, performance, beginner
if letter in ("N", "n"):
box_list = [1, 2, 4, 6, 7, 9, 10, 12, 13, 15, 16, 18, 19, 21]
if letter in ("O", "o"):
box_list = [1, 2, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16, 18, 19, 20, 21]
if letter in ("P", "p"):
box_list = [1, 2, 4, 6, 7, 8, 10, 13, 16, 19]
if letter in ("Q", "q"):
box_list = [2, 4, 6, 8, 9, 12, 15, 18, 21]
if letter in ("R", "r"):
box_list = [1, 2, 4, 6, 7, 8, 10, 12, 13, 15, 16, 18, 19, 21]
if letter in ("S", "s"):
box_list = [2, 3, 4, 7, 11, 15, 18, 19, 20]
if letter in ("T", "t"):
box_list = [1, 2, 3, 5, 8, 11, 14, 17, 20]
if letter in ("U", "u"):
box_list = [1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16, 18, 19, 20, 21]
if letter in ("V", "v"):
box_list = [1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16, 18, 20]
if letter in ("W", "w"):
box_list = [1, 3, 4, 6, 7, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 21]
if letter in ("X", "x"):
box_list = [1, 3, 4, 6, 7, 9, 11, 13, 15, 16, 18, 19, 21]
if letter in ("Y", "y"):
box_list = [1, 3, 4, 6, 7, 9, 11, 14, 17, 20]
if letter in ("Z", "z"):
box_list = [1, 2, 3, 6, 9, 11, 13, 16, 19, 20, 21]
if letter == "?":
box_list = [2, 4, 6, 9, 11, 14, 20]
if letter == ".":
box_list = [19]
if letter == "-":
box_list = [4, 5, 6]
for box_number in box_list:
x_position = box_number % 3
y_position = box_number // 3
if box_number % 3 == 0:
x_position = 3
y_position -= 1
x_position -= 1
rect((x_position * 50) + 10, (y_position * 50) + 10, 50, 50)
drawly.draw()
drawly.done()
As you can see, to turn the boxes on and off, I use if statements that assign box_list its values based on the input. How can I optimize the assignment of these numbers to box_list without using a billion if statements?
Answer: mapping
... without using a billion if statements? | {
"domain": "codereview.stackexchange",
"id": 45499,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner",
"url": null
} |
python, performance, beginner
Answer: mapping
... without using a billion if statements?
Use a dict:
char_to_appearance = {
"A": ("red", [2, 4, 6, 7, 9, 10, 11, 12, 13, 15, 16, 18, 19, 21]),
...
"?": (None, [2, 4, 6, 9, 11, 14, 20]),
".": (None, [19]),
"-": (None, [4, 5, 6]),
}
I started out naming it char_to_boxes, but then I saw
a subset of letters produce color changes.
It's possible you would prefer to handle color separately.
downcase
Expressions like ... in ("A", "a"): are nice enough.
But given that we never draw different glyphs for upper vs lower,
we may as well downcase from the get go:
letter = letter.lower(), or perhaps
letter = input(prompt).lower()
BTW the prompt neglects to mention the - dash punctuation mark.
plural container
box_list = []
Yes, we know it's a list, we can see that.
Please avoid suffixes such as _dict or _list.
This is a container.
It describes more than one box.
So pluralize it: boxes = []
use a function
The for box_number in box_list: code should
be packaged up as a function which has a
single responsibility.
def draw_character(char: str) -> None:
color, boxes = char_to_appearance[char]
if color:
drawly.set_color(color)
for box in boxes:
x, y = box % 3 - 1, box // 3
# I don't understand what motivated this `if` -- please # comment
if box % 3 == 0:
x_position = 2
y_position -= 1
w = 50 # width (in pixels) of each square box
rect(w * x + 10, w * y + 10, w, w)
drawly.draw() | {
"domain": "codereview.stackexchange",
"id": 45499,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner",
"url": null
} |
python, performance, beginner
I feel it should be caller's responsibility
to call drawly.done().
At some point you might change the signature
so the function accepts both a character
and a screen position at which to draw the character.
Or, IDK, maybe caller should do that, using drawly.start().
I found no drawly documentation on
pypi,
but rect() appears to use an offset supplied to start().
I feel caller, rather than this routine, should worry about
applying that (+10, +10) offset.
With all that in hand, you'd be ready for def draw_string ! | {
"domain": "codereview.stackexchange",
"id": 45499,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, beginner",
"url": null
} |
c++, beginner, programming-challenge
Title: Advent of Code 2023 day 1: Trebuchet (Part 2)
Question: Task:
The task involves analyzing a calibration document containing lines of text. Each line represents a calibration value that needs to be recovered by extracting the first and last digits (which may also be spelled out as words) and combining them into a two-digit number. The goal is to find the sum of all these calibration values.
For example:
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281.
Code:
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <regex>
static int get_digit(const std::string &line, const std::regex &accept)
{
static const auto digit_names{std::to_array(
{"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"})};
ptrdiff_t digit = -1;
std::smatch match;
if (std::regex_search(line, match, accept)) {
const auto it = std::find(std::begin(digit_names),
std::end(digit_names), match.str(1));
if (it != std::end(digit_names)) {
digit = std::distance(std::begin(digit_names), it);
} else {
digit = std::stoi(match.str(1));
}
}
return digit;
}
static int get_first_digit(const std::string &line)
{
const std::regex accept(
R"((\d|zero|one|two|three|four|five|six|seven|eight|nine))");
return get_digit(line, accept);
}
static int get_last_digit(const std::string &line)
{
const std::regex accept(
R"(.*(\d|zero|one|two|three|four|five|six|seven|eight|nine))");
return get_digit(line, accept);
}
static int calc_calibration_total(std::istream &in_file)
{
std::string line{};
int sum{}; | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
static int calc_calibration_total(std::istream &in_file)
{
std::string line{};
int sum{};
while (std::getline(in_file, line)) {
const int first_digit = get_first_digit(line);
if (first_digit != -1) {
sum += first_digit * 10 + get_last_digit(line);
}
}
return sum;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
std::cerr << "Usage: " << (argv[0] ? argv[0] : "aoc_1b") << " <filename>\n";
return EXIT_FAILURE;
}
std::ifstream in_file(argv[1]);
const int sum{calc_calibration_total(in_file)};
if (!in_file.eof()) {
std::cerr << "Error: failed to read input file " << argv[1] << " - "
<< std::error_code{errno, std::generic_category()}.message()
<< ".\n";
return EXIT_FAILURE;
}
std::cout << sum << "\n";
}
Review Request:
General coding comments, style, bad/outdated practices et cetera.
Answer: I don’t see that regular expressions are really necessary here. This does not seem like a situation that requires their complexity or cost. On top of that, by doing two separate regexes, you have shot yourself in the foot, and introduced a bug.
You don’t need regular expressions
Let’s consider the basics of the first part of what you are trying to do. You have an input string, and you have a list of strings, and you want to find the first of that list of strings in the input string.
So:
constexpr auto needles = std::to_array<std::string_view>({
"0", "1", "2", ..., "9",
"zero", "one", "two", ..., "nine"
});
auto found = std::ranges::subrange{std::ranges::end(input), std::ranges::end(input)};
for (auto&& needle : needles)
{
auto const result = std::ranges::search(input, needle);
if (std::ranges::begin(result) < std::ranges::begin(found))
found = result;
}
if (std::ranges::begin(found) == std::ranges::end(input))
throw std::runtime_error{"no numbers in input"}; | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
Other than a few fairly minor details, that’s basically the first half of the problem solved. The second half—finding the last occurrence—isn’t much different.
Here are some tips to improve the above:
Instead of an array of just the needle strings, make an array of tuples combining each needle string with the number it maps to. It makes no sense to compute the number with std::distance() or, worse, std::stoi() when you can just encode that data at compile time. Plus, keeping the string and number together means you don’t need to care about the order of needles in the needle array anymore, which means you can sort it (at compile-time), which will help if you have needles that are substrings of other needles.
If the input strings are very long, you could use searchers instead of the vanilla search algorithm.
You don’t need to search the whole input string for each needle. Once you’ve found a needle at position \$x\$, you only need to search for another needle of length n from the beginning to position \$(x - 1) + n\$. If the needle is found after that, then it is after the previously found needle (or concurrent with it, in the case that some needles are substrings of other needles).
Regular expressions are overkill.
You can’t break this into two independent sub-problems
Your code basically looks like this:
auto get_first_digit(std::string const& line)
{
// ...
}
auto get_last_digit(std::string const& line)
{
// ...
}
auto calc_calibration_total(std::istream& in_file)
{
// for each line in in_file
{
auto digit_1 = get_first_digit(line);
auto digit_2 = get_last_digit(line);
// ... etc.
}
// ... etc.
} | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
// ... etc.
}
// ... etc.
}
This structure cannot work, no matter what is in the commented bits.
Easier than trying to explain why, I can demonstrate. Try running your algorithm with the line “sevenine”.
Want an even more damning example? Try the line “3”. Or “three”.
Do you understand the problem now? Unless it is intended that the first and last digit strings overlap… and even to wholly overlap… then you cannot isolate the search for the last digit from the search for the first digit. Once you find the first digit, you need that information for the search for the last digit. Specifically, you need to know where the first digit ends, so that you can start the search for the last digit after that.
If you wanted to solve this with regexes alone, then you would need to do both searches at once. Either that, or once the first digit string is found, you need to create a whole new string with everything up to the end of that first digit string removed. Either way is expensive.
With simple searches, you don’t need to create whole new strings for the second part of the search. You can just use the iterators from the first search to mark where to begin the second.
Whatever method you use, the point is that the second search cannot be fully independent of the first. Somehow, you need to carry information from the first search over to the second, to let it know where to start the search from. Or, put another way, the search for the second digit has to know where not to look (that is, it is not to look in the place where the first digit was found).
Code review
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <regex> | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
There are quite a few includes here that are not necessary, and a few necessary includes that are missing. I don’t see any reason for <cstdint> or <cstring>. On the other hand, I see std::error_code but no <system_error>.
static int get_digit(const std::string &line, const std::regex &accept)
I notice you’ve made all your functions static. There is no real need for this. I suppose it’s one of those “tricks” that are popular in “coding challenge”-style C++. But it strikes me as having dubious benefit.
Now, as for the const std::string &line style, that is C-style layout, not C++-style. In C++, we keep the type modifiers with the type.
C-style: const std::string &line
C++-style: const std::string& line
C++-style (east const): std::string const& line
static const auto digit_names{std::to_array(
{"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"})};
I’m a little baffled by the use of std::to_array() here.
The purpose of std::to_array() is to handle situations where you only want partial deduction of std::array’s template parameters. Specifically, it is for when you want to force the type, but still deduce the count. That means you almost never want to write just std::to_array({...}); you almost always want std::to_array<type>({...}). Without the <type>, you might as well just write std::array{...}.
Which means, in this case:
static const auto digit_names{
std::array{
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"
}
};
// or:
static const std::array digit_names{
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"
}; | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
But do bear in mind that this is creating an array of char const*… which is not great. Better would be to create an array of string views, because when comparing strings to string views, the comparison can be short-circuited if the size is not the same (whereas, for a char const*, it would effectively have to do std::strcmp() every time).
ptrdiff_t digit = -1;
This should be std::ptrdiff_t to begin with (and you should include the right header)… except… why is it not int? That is what you want it to be in the end in any case. What is the point of making it std::ptrdiff_t?
if (std::regex_search(line, match, accept)) {
const auto it = std::find(std::begin(digit_names),
std::end(digit_names), match.str(1));
if (it != std::end(digit_names)) {
digit = std::distance(std::begin(digit_names), it);
} else {
digit = std::stoi(match.str(1));
}
} | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
Oof, it makes my skin crawl how inefficient this is. It’s not even your fault. I’ll let you in on a dirty little secret. The standard C++ regex library is TERRIBLE. It’s design is terrible, and most implementations are terrible. I never use it. I rarely use regex in C++ at all, but when I do, I use Boost.Regex. (I’ve also been very interested in trying out Hana Dusíková’s CTRE, but haven’t had a chance yet.) But std::regex? .
(There is a particularly hilarious example that I vaguely recall from Dusíková’s CTRE proposal paper, where she was benchmarking different regex libraries, and in one case, a match that took around 20 seconds with Boost.Regex took 20 MINUTES with std::regex.)
One problem with std::regex is that is entirely based on strings. It predates string views. So, for example, when you do match.str(1), instead of just getting a view of the matched needle in line, a whole new string has to be constructed. Just to do the lookup in your digit names table. (To be fair, your needles are very short, so the small string optimization almost certainly applies. Still.)
And then there’s std::stoi(). As with std::regex, std::stoi() is a raging dumpster fire, and a performance-sucking black hole in your program. The problem with std::stoi() is not just that it requires strings (doesn’t really matter here, because you are forced to construct a string anyway thanks to std::regex). The thing that people don’t realize about std::stoi() until the day it bites them in the ass is that std::stoi() is locale-dependent. You are assuming that “0123456789” are digits… but you may find that the current locale thinks otherwise.
There’s no easy fix for std::regex (though Boost.Regex is mostly a far superior drop-in replacement). But at least for std::stoi() we now have a much better alternative: std::from_chars().
HOWEVER…
You’re already doing a lookup (in the digit_names array). Why not just go all-in and fully use the lookup? | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
static auto get_digit(std::string const& line, std::regex const& accept)
{
constexpr auto digits = std::to_array<std::tuple<std::string_view, int>>({
{ "0", 0 },
{ "1", 1 },
{ "2", 2 },
// ...
{ "9", 9 },
{ "zero", 0 },
{ "one", 1 },
{ "two", 2 },
// ...
{ "nine", 9 }
}); | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
constexpr auto project_string_view =
[] (auto&& digit) { return std::get<std::string_view>(d); };
std::smatch match;
if (std::regex_search(line, match, accept))
{
auto const it = std::ranges::find(digits, match.str(1), project_string_view);
return std::get<int>(*it);
}
else
{
throw std::invalid_argument{"no digit in line"};
}
}
As you can see, it simplifies the function considerably. You could use the same digits data for the search. The regex is basically just:
auto const regex = std::regex{
'('
+ (digits
| std::views::elements<0>
| std::views::join_with('|')
| std::ranges::to<std::string>
)
+ ')'
};
Or, if you want to avoid the bug I mentioned and search for both digits at once:
auto const regex_disjunction = '('
+ (digits
| std::views::elements<0>
| std::views::join_with('|')
| std::ranges::to<std::string>
)
+ ')'
;
auto const regex = std::regex{
".*?"
+ regex_disjunction
".*"
+ regex_disjunction
".*"
};
I’m not suggesting you do this, of course. But you could.
static int calc_calibration_total(std::istream &in_file)
{
std::string line{};
int sum{};
while (std::getline(in_file, line)) {
const int first_digit = get_first_digit(line);
if (first_digit != -1) {
sum += first_digit * 10 + get_last_digit(line);
}
}
return sum;
} | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
This works, I guess, but it’s not very flexible. What if the data is already loaded in a vector of strings?
The modern way to handle something like this would be to use composable range operations. So, for example:
template <std::input_range R>
requires std::convertible_to<std::ranges::range_value_t<R>, std::string_view>
constexpr auto calculate_trebuchet_calibration(R&& lines)
{
return std::ranges::fold_left(
lines
| std::views::transform(parse_digits)
| std::views::transform(generate_calibration_value)
,
0,
std::plus<>{}
);
}
Note that there is not a single branch or loop in view. The logic is clean and simple; a straight line. You literally cannot screw it up.
(It is unfortunate that the ranges library doesn’t allow a terminating reduction function. It would have been nice to be able to write:
template <std::input_range R>
requires std::convertible_to<std::ranges::range_value_t<R>, std::string_view>
constexpr auto calculate_trebuchet_calibration(R&& lines)
{
return lines
| std::views::transform(parse_digits)
| std::views::transform(generate_calibration_value)
| xxx::reduce(std::plus<>{})
;
// ... or:
return lines
| std::views::transform(parse_digits)
| std::views::transform(generate_calibration_value)
| xxx::sum
;
}
But, alas, we have to work with the tools we have.)
Since you intend to read from a stream, you could write a helper function:
auto calculate_trebuchet_calibration(std::istream& in)
{
auto const result = calculate_trebuchet_calibration(std::views::istream<std::string>(in));
if (not in)
throw std::runtime_error{"failed to read trebuchet calibration data from file"};
return result;
}
Then it’s just a matter of writing the transform functions:
auto parse_digits(std::string_view) -> std::tuple<digit, digit>;
auto generate_calibration_value(std::tuple<digit, digit>) -> int; | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
Put a pin in all that, because this is not the only way to do this, and may not be the best way for this particular problem. Let’s look at main():
std::ifstream in_file(argv[1]);
const int sum{calc_calibration_total(in_file)};
if (!in_file.eof()) {
std::cerr << "Error: failed to read input file " << argv[1] << " - "
<< std::error_code{errno, std::generic_category()}.message()
<< ".\n";
return EXIT_FAILURE;
}
This is a bad pattern. If there was an error reading the input file, that should have been determined in the function reading the input file. Trying to do it here, after the fact, is a hack.
Furthermore, .eof() is not an error status, nor should it be interpreted as one. If you want to determine whether an error occurred, you either need to check .fail() and .bad(), or, more simply, just use the stream’s bool conversion. In other words, if (!in_file.eof()) is the wrong way to check for an error; it should be if (!in_file).
If you want to properly handle IOstream errors, I would suggest the first step is always enabling exceptions on the stream. That will save you a lot of headaches, to begin with. If you don’t want to do that, then you should at least do a check for .is_open() before starting anything else.
Next, you need a proper type to parse. Something like:
class trebuchet_calibration_data
{
public:
friend auto operator>>(std::istream& in, trebuchet_calibration_data& data)
-> std::istream&
{
auto s = std::string{};
if (in >> s)
{
// Extract the two digits here.
//
// If the extraction is successful, then:
// data.digit_1 = digit_1;
// data.digit_2 = digit_2;
//
// If the extraction was *not* successful, then:
// in.setstate(std::ios_base::failbit);
}
return in;
}
int digit_1 = 0;
int digit_2 = 0;
}; | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
return in;
}
int digit_1 = 0;
int digit_2 = 0;
};
With that, error handling is mostly automatic. while (std::getline(in_file, line)) will stop on the first error, as will std::views::istream. This is the proper way to work with IOstreams.
So, perhaps the best idea is to make a custom type like the above, and a program structure like:
namespace trebuchet_calibration {
enum class calibration_error
{
// list of potential errors
};
// <system_error> stuff...
template <>
struct std::is_error_code_enum<calibration_error> : true_type
{};
class error_category_t : public std::error_category
{
public:
auto name() const noexcept -> char const* override
{
return "trebuchet_calibration";
}
auto message(int value) const -> std::string override
{
switch (static_cast<calibration_error>(value))
{
// ...
default:
return "{unrecognized error}";
}
}
};
auto error_category() -> std::error_category const&
{
static auto const cat = error_category_t{};
return cat;
}
auto make_error_code(calibration_error value) -> std::error_code
{
return std::error_code{static_cast<int>(value), error_category()};
}
class calibration_data
{
public:
static auto parse(std::string_view s)
-> std::expected<calibration_data, calibration_error>
{
// Try to extract the two digits from the string view.
};
friend auto operator>>(std::istream& in, calibration_data& data)
-> std::istream&
{
auto s = std::string{};
if (in >> s)
{
if (auto const result = parse(s); result)
data = *result;
else
in.setstate(std::ios_base::failbit);
}
return in;
}
constexpr auto calculate_value() const noexcept
{
return (digit_1 * 10) + digit_2;
}
int digit_1 = 0;
int digit_2 = 0;
}; | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
int digit_1 = 0;
int digit_2 = 0;
};
template <std::input_range R>
requires std::convertible_to<std::ranges::range_value_t<R>, calibration_data>
constexpr auto calculate(R&& data)
{
return std::ranges::fold_left(
lines | std::views::transform(&calibration_data::calculate_value),
0,
std::plus<>{}
);
}
template <std::input_range R>
requires std::convertible_to<std::ranges::range_value_t<R>, std::string_view>
constexpr auto calculate(R&& strings)
{
return calculate(strings
| std::views::transform([] (auto&& s)
{
auto result = calibration_data::parse(s);
if (not result)
throw std::system_error{make_error_code(result.error())};
return *result;
}
)
);
}
auto calculate(std::istream& in)
{
auto const result = calculate(std::views::istream<calibration_data>(in));
if (not in)
throw std::runtime_error{"failed to parse trebuchet calibration data"};
return result;
}
} // namespace trebuchet_calibration
auto handle_errors(std::string_view prog) -> int
{
try
{
throw;
}
catch (no_filename_given_error const&)
{
std::cerr << "Usage: " << prog << " <filename>\n";
}
catch (std::exception const& x)
{
std::cerr << prog << ": " << x.what() << '\n';
}
catch (...)
{
std::cerr << prog << ": unknown error\n";
}
return EXIT_FAILURE;
}
auto main(int argc, char* argv) -> int
{
try
{
if (argc != 2)
throw no_filename_given_error{};
auto in_file = std::ifstream{argv[1]};
if (not in_file.is_open())
throw open_file_error{argv[1]};
auto const result = trebuchet_calibration::calculate(in_file);
std::cout << result << '\n';
}
catch (...)
{
return handle_errors(argv[0] ? argv[0] : "aoc_1b");
}
} | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
c++, beginner, programming-challenge
That’s just a very rough approximation of one kind of solution. Most of it is error handling (the <system_error> stuff is very verbose).
It might even be better to have the calculate() functions return a expected<int, calibration_error> instead of just an int, and avoid throwing anything at all. You’d have to write a monadic version of std::plus<> for the fold, but that wouldn’t be hard.
Anywho, that should be enough for a review.
In summary:
You don’t need regular expressions for this.
Even if you do, you should avoid std::regex.
If you’re going to be using a lookup map anyway, you might as well go all-in, and lookup all possible values (rather than splitting the logic into digits and “digit words”), and include other useful information (like the numeric value of the digit).
You cannot separate finding the first and last digits into two isolated problems. You need to pass information form one task to the next… specifically, where not to search (because something was found there already).
Don’t try to “guess” whether an error occurred on reading input by circumstantial evidence (like whether EOF was hit). Either use the correct error signalling IOStream bit (which would be failbit in this case), or use exceptions or some other legit error-signalling mechanism.
Modern C++ avoids explicit loops and branches by chaining operations on ranges, so tasks read like a simple sequence of steps. This is what you should strive for.
Making a few custom types can really help with the above.
Happy coding! | {
"domain": "codereview.stackexchange",
"id": 45500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, programming-challenge",
"url": null
} |
beginner, random, wrapper, lua
Title: RandomNumber wrapper in Lua
Question: This is a wrapper I wrote for math.random(). I have a larger program that will create a JSON file to 'load' from when I want to resume. However my program heavily used math.random() which made it hard to debug and test the program because different results would occur depending on if the program was started fresh, or from a load file.
This wrapper lets you "resume" from a random seed.
RandomNumber.lua
--[[
RandomNumber - Lua Class for Generating and Managing Random Numbers
The RandomNumber class is designed to facilitate the generation of random numbers
using Lua's built-in math.random function. It includes features for tracking the
number of generated random numbers and the ability to 'jump' to a specific iteration.
This functionality is particularly useful for debugging and testing. Example if
a program is to save its state and 'resume' and we want numbers generated to not
reset,
Usage:
local rng = RandomNumber:new(seed) -- Instantiate class, 'seed' is optional but suggested
rng:jumpToIteration(10) -- Jump to the 10th iteration. Next generate() method will be the 11th
rng:generate() -- generate a random number
--]]
---@class RandomNumber
local RandomNumber = {}
-- Wrapper for math.random() in case we want to change in the future
local function generateRandomNumber(a, b)
if a and b then
return math.random(a, b)
elseif a then
return math.random(a)
end
return math.random()
end
---@return RandomNumber
function RandomNumber:new(seed)
---@type RandomNumber
local randomNumber = {}
self = self or randomNumber
self.__index = self
setmetatable(randomNumber, self)
randomNumber.count = 0
if seed then
math.randomseed(seed)
randomNumber.seed = seed
end
return randomNumber
end | {
"domain": "codereview.stackexchange",
"id": 45501,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, random, wrapper, lua",
"url": null
} |
beginner, random, wrapper, lua
return randomNumber
end
-- Reset the RandomNumber object with a new seed.
---@param seed number
function RandomNumber:reset(seed)
math.randomseed(seed)
self.count = 0
self.seed = seed
end
function RandomNumber:generate(a, b)
self.count = self.count + 1
return generateRandomNumber(a, b)
end
-- Jumps to a point in the random number sequence.
-- Warning: Will produce new random seed if no seed was ever given
---@param iteration number
function RandomNumber:jumpToIteration(iteration)
if type(iteration) ~= "number" or iteration < 0 then
error("Invalid argument, expected a number 0 or greater: " .. iteration)
end
local difference = iteration - self.count
if difference > 0 then
for _ = 1, difference do
generateRandomNumber()
end
elseif difference < 0 then
self = RandomNumber:new(self.seed)
self:jumpToIteration(iteration)
end
self.count = iteration
end
return RandomNumber
RandomNumberTest.lua:
-- Import LuaUnit module
local lu = require('luaunit')
-- Import the RandomNumber class
local RandomNumber = require('RandomNumber')
-- Test the RandomNumber class
TestRandomNumber = {}
---@class RandomNumber
local rng
local firstNumberInSeq = '0.23145237586596'
local secondNumberInSeq = '0.58485671559801'
local hundredthNumberInSeq = '0.43037202063051'
function TestRandomNumber:setUp()
-- Set a fixed seed value for reproducibility in tests
rng = RandomNumber:new(12345)
end
-- Function to round a number to a specified decimal place
local function round(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end | {
"domain": "codereview.stackexchange",
"id": 45501,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, random, wrapper, lua",
"url": null
} |
beginner, random, wrapper, lua
function TestRandomNumber:testGenerate()
-- use tostring method, otherwise the comparison fails between floats
-- Numbers are based on math.random(), given seed 12345
lu.assertEquals(tostring(rng:generate()), firstNumberInSeq)
lu.assertEquals(tostring(rng:generate()), secondNumberInSeq)
end
function TestRandomNumber:testJump()
rng:jumpToIteration(99)
lu.assertEquals(tostring(rng:generate()), hundredthNumberInSeq)
end
function TestRandomNumber:testGenerateAndJump()
for _=1, 50 do
rng:generate()
end
rng:jumpToIteration(99)
lu.assertEquals(tostring(rng:generate()), hundredthNumberInSeq)
end
function TestRandomNumber:testJumpBackwards()
for _=1, 50 do
rng:generate()
end
rng:jumpToIteration(1)
lu.assertEquals(tostring(rng:generate()), secondNumberInSeq)
end
function TestRandomNumber:testJumpZero()
for _=1, 99 do
rng:generate()
end
-- jump to the iteration 0
rng:jumpToIteration(0)
-- Should be 1st
lu.assertEquals(tostring(rng:generate()), firstNumberInSeq)
end
function TestRandomNumber:testJumpToSameSpot()
for _=1, 99 do
rng:generate()
end
rng:jumpToIteration(99)
lu.assertEquals(tostring(rng:generate()), hundredthNumberInSeq)
end
function TestRandomNumber:testReset()
rng:generate()
rng:jumpToIteration(105)
rng:reset(12345)
lu.assertEquals(tostring(rng:generate()), firstNumberInSeq)
lu.assertEquals(tostring(rng:generate()), secondNumberInSeq)
end
function TestRandomNumber:testJumpToIterationInvalidArgumentNegative()
-- Use pcall to catch the error
local success, errorMessage = pcall(function()
rng:jumpToIteration(-1)
end)
-- Check that pcall was not successful (error was thrown)
lu.assertFalse(success)
-- Check that the error message is as expected
lu.assertStrContains(errorMessage, "Invalid argument")
end | {
"domain": "codereview.stackexchange",
"id": 45501,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, random, wrapper, lua",
"url": null
} |
beginner, random, wrapper, lua
function TestRandomNumber:testJumpToIterationInvalidArgumentNaN()
-- Use pcall to catch the error
local success, errorMessage = pcall(function()
rng:jumpToIteration('11')
end)
-- Check that pcall was not successful (error was thrown)
lu.assertFalse(success)
-- Check that the error message is as expected
lu.assertStrContains(errorMessage, "Invalid argument")
end
function TestRandomNumber:testJumpToIterationNilSeed()
local rngTarget = RandomNumber:new()
lu.assertNil(rngTarget.seed)
rngTarget:generate()
rngTarget:generate()
rngTarget:jumpToIteration(0)
lu.assertNil(rngTarget.seed)
rngTarget:generate()
rngTarget:generate()
end
function TestRandomNumber:testJumpToIterationWithSeed()
local rngTarget = RandomNumber:new(1550)
lu.assertEquals(1550, rngTarget.seed)
local firstValue = rngTarget:generate()
local secondValue = rngTarget:generate()
rngTarget:jumpToIteration(0)
lu.assertEquals(1550, rngTarget.seed)
local newValue1 = rngTarget:generate()
local newValue2 = rngTarget:generate()
lu.assertEquals(firstValue, newValue1)
lu.assertEquals(secondValue, newValue2)
end
-- Run the tests
os.exit(lu.LuaUnit.run())
random-number-1.0.0-2.rockspec (Included in case suggestions can be made to it)
package = "random-number"
version = "1.0.0-2"
source = {
url = "git://github.com/LionelBergen/RandomNumber",
tag = "master",
}
description = {
summary = "RandomNumber generator and manager.",
detailed = [[
This is a wrapper for Lua's builtin math.random. Purpose is for debugging & testing applications
that use random numbers. Having numbers be reproduced the same way makes for easier testing & debugging
]],
homepage = "https://github.com/LionelBergen/RandomNumber",
}
dependencies = {
"lua >= 5.1",
}
build = {
["type"] = "builtin",
modules = {
randomnumber = "RandomNumber.lua"
}
} | {
"domain": "codereview.stackexchange",
"id": 45501,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, random, wrapper, lua",
"url": null
} |
beginner, random, wrapper, lua
Answer: The main issue: side effects
The main issue is that you are using a random which there is only a single seed, shared between any code running on the platform. This is a questionable design by Lua (and many other runtimes) to start with, but it does mean that the state of your program may be influenced by calls to math.random() or math.randomseed(x) that simply skip your wrapper.
Moreover, the calls to randomseed(x) may influence other parts that rely on the random number generator, leading to weird interactions between code that does use the wrapper and code that doesn't. In other words, your code has significant side effects on the state of the runtime.
One way would be to implement a RNG yourself, preferably the same one that Lua uses at the moment. In that case the results from your RandomNumber and math.random() are decoupled.
Implementation code
RandomNumber - Lua Class for Generating and Managing Random Numbers
Just the name RandomNumber nor the first line clearly shows what the class can be used for. A more clear name should be considered, such as RepeatableRandomNumber.
function RandomNumber:jumpToIteration(iteration)
It is unclear how the user would be able to know the iteration, as calls to any code may increase the iteration. Furthermore, this code may skip your interesting wrapper entirely.
It would be a good idea to at least to be able to retrieve the count that is kept so that the user can retrieve the iteration before or after retrieving a random at a specific point.
function RandomNumber:generate(a, b)
local function generateRandomNumber(a, b)
I'm wondering why the parameter names are called a and b while they are called m and n in the Lua documentation of math.random. That just makes things harder to understand.
Similarly, I'm not sure why there would be a count which counts the iterations. It might as well be called iteration in my opinion, so that there is just one term to deal with. | {
"domain": "codereview.stackexchange",
"id": 45501,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, random, wrapper, lua",
"url": null
} |
beginner, random, wrapper, lua
Missing documentation of:
function RandomNumber:generate(a, b)
The documentation of this method is missing. It should indicate that the iteration count is increased, and it should both summarize and reference the documentation for math.random. This is the main function of the library and although it may be clear to you what the function does, it should at least greet any other user with easy to understand documentation.
Test code
Beware that the Lua documentation doesn't seem to explicitly indicate a specific RNG implementation, just saying that "This function is an interface to the underling pseudo-random generator function provided by C." which is extremely loose. That also means that storing expected values within floating point in the test code is dangerous, as any change in the underlying implementation will result in different values being generated.
In general these kind of pseudo number generators will produce specific ranges of random numbers as long as the runtime implementation implements the same algorithms.
local function round(num, numDecimalPlaces)
This is an unused function. I'm not sure why it would be in the test code. There is no need to test the correctness of the random numbers if this is just a wrapper; I'd just test if the minimum and maximum values can indeed be returned (obviously from a small range).
lu.assertEquals(firstValue, newValue1)
Yes, that trap was setup by yourself :). If you'd just named it this way firstvalue -> a1 and secondValue -> b1 then you could have named the second run a2 and b2.
General remarks
Naming and code style seems OK, other than the remarks that have already been made.
Tests seem to take boundary values into account and cover most if not all of the code, which is generally a good idea. | {
"domain": "codereview.stackexchange",
"id": 45501,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, random, wrapper, lua",
"url": null
} |
c++, pointers, trie
Title: Trie implementation using std::shared_ptr
Question: I've implemented a basic Trie that is supposed to work only with lowercase English letters.
class TrieNode {
public:
array<shared_ptr<TrieNode>, 26> children;
bool isWord;
TrieNode(bool _isWord = false) : isWord{_isWord} {
}
};
class Trie {
public:
Trie() : root{make_shared<TrieNode>(TrieNode())} {
}
void insert(const string& word) {
auto p = root;
for (const auto& ch : word) {
const auto idx = ch - 'a';
if (p->children[idx] == nullptr) {
p->children[idx] = make_shared<TrieNode>(TrieNode());
}
p = p->children[idx];
}
p->isWord = true;
}
bool search(const string& word, bool prefix = false) {
auto p = root;
for (const auto& ch : word) {
const auto idx = ch - 'a';
if (p->children[idx] == nullptr) {
return false;
}
p = p->children[idx];
}
if (prefix) {
return true;
}
return p->isWord;
}
bool startsWith(const string& prefix) {
return search(prefix, true);
}
private:
shared_ptr<TrieNode> root;
};
Is the use of shared_ptr appropriate here? Could I get more efficiency from this code?
Answer: Use std::unique_ptr instead of std::shared_ptr
You are never sharing your std::shared_ptrs, so it is much better to use std::unique_ptr instead. std::unique_ptr uses less memory and is more efficient.
Call std::make_unique() without arguments
When you call
p->children[idx] = make_shared<TrieNode>(TrieNode());
The expression TrieNode() is creating a temporary TrieNode object, and then that is copied by std::make_shared(). This is unnecessary though, just call make_shared<TrieNode>(). Or with std::unqiue_ptr:
p->children[idx] = make_unique<TrieNode>(); | {
"domain": "codereview.stackexchange",
"id": 45502,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, pointers, trie",
"url": null
} |
c++, pointers, trie
root does not need to be a pointer
You can just make root be a TrieNode directly. Then you can also remove the default constructor.
Alternative ways to store children
You need some way to allocate memory for children. Your approach of doing something like std::array<std::unique_ptr<TrieNode>, 26> is one possible way to do that. However, there are others. The problem with your approach is that every node, even if it is a leaf node, stores 26 pointers. That's 208 bytes on a 64-bit system. It would be nice if you could avoid that, at least for the leaf nodes. So consider this instead:
std::unique_ptr<std::array<TrieNode, 26>> children;
Now you only have one pointer (8 bytes on a 64-bit system) in a TrieNode, which reduces the memory usage of leaf nodes quite a bit.
There are many other ways to store children; you could use a std::vector<TrieNode>, a std::unordered_map<char, TrieNode>, or do something completely different. There are tradeoffs between memory usage, performance and easy of programming. Which approach is better also depends on how deep and dense your tries are.
How compact you can store your trie into memory is going to have a big influence on how efficient it will be; the smaller it is the less memory bandwidth will be necessary and the more cache memory will be effective. | {
"domain": "codereview.stackexchange",
"id": 45502,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, pointers, trie",
"url": null
} |
python, python-3.x
Title: Look and Say sequence function
Question: This is my first rough attempt at creating a function to return the nth number within the look-and-say sequence. I'm pretty sure there are some ways to simplify it, even given my current approach. Also, I feel kind of guilty that the first number is hard-coded.
def look_and_say(iterations):
if iterations == 0:
return 1
seq = '11'
for _ in range(iterations-1):
new_seq = ''
num = ''
count = int
for i in range(len(seq)):
if seq[i] != num:
if i != 0:
new_seq += str(count) + num
num = seq[i]
count = 1
else:
count += 1
if i == len(seq)-1:
new_seq += str(count) + num
seq = new_seq
return int(seq)
Answer: There are some problems with your code.
feeling guilty
Hard coding an initial value is perfectly ok.
However I do not agree it is the 'first' value.
I consider it the second one. If we initialize seqlike
seq = '1'
we also get rid of the ugly loop counter and get a nicer one
for _ in range(iterations):
Still, we have the value coded twice, once in
return 1
once in the new line
seq = '1'
How to fix? E. g.
call your function recursively
seq = str(look_and_say(0))
or, the other way round
return int(seq)
Oh wait, the latter looks familiar, it is the final return line. So, do we need the if clause at all? No.
The for loop safely incorporates the "no runs at all" case. So we start our function like
def look_and_say(iterations):
seq = '1'
for _ in range(iterations):
Note: The if clause is required if you go for recursion instead of the outer loop.
Loop like a pro
for i in range(len(seq)):
if seq[i] != num:
is considered (exceptionally) bad style.
In Python we loop like
for elem in seq:
if elem != num: | {
"domain": "codereview.stackexchange",
"id": 45503,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
is considered (exceptionally) bad style.
In Python we loop like
for elem in seq:
if elem != num:
and avoid accessing elements via index.
If the index is required as well (like in your case) we loop like
for i, e in enumerate(seq):
if e != num:
if i != 0:
Even if you need the index only you may loop like
for i, _ in enumerate(seq):
if i != 0:
Inner loop
The body has a high complexity as there are 4 cases to be handled.
The regular cases within a string "char change" and "char equality"
and the special cases "loop break in" handling initialisation and
"loop break out" handling tear down (reporting).
This pattern is very common in e. g. loops working on a stream in a receive callback.
In your case such a state machine changing state is hard to read. You should go for
algorithmic (and testable) steps, even if this requires you to loop multiple times.
Still, if you stick to your loop like that, Python offers the else clause on a for loop,
which is executed finally after a regularly exhausted loop.
for i in range(len(seq)):
# ...
if i == len(seq)-1:
new_seq += str(count) + num
may read
for i in range(len(seq)):
# ...
else:
new_seq += str(count) + num
We also can eliminate the index i completely as we use num or count to check if num is holding a digit.
The code looks now like
def look_and_say(iterations):
seq = '1'
for _ in range(iterations):
new_seq = ''
num = ''
count = 0
for e in seq:
if e != num:
if count:
new_seq += str(count) + num
num = e
count = 1
else:
count += 1
else:
new_seq += str(count) + num
seq = new_seq
return int(seq) | {
"domain": "codereview.stackexchange",
"id": 45503,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
Inner loop II
The reason for the complexity of the inner loop is that it is a superposition of two loops,
the outer one looping over sequences of equal characters changing e. g. num,
the inner one counting the equal characters changing count.
You could make nested loops instead with the help of a generator.
In our example we can eliminate the inner one with library functions. The string representation of seq
allows us to consume equal character sequences with lstrip()
def look_and_say(iterations):
seq = '1'
for _ in range(iterations):
new_seq = ''
while seq:
num = seq[0]
remain = seq.lstrip(num)
count = len(seq) - len(remain)
new_seq += str(count) + num
seq = remain
seq = new_seq
return int(seq)
num and count are now helper variables not needing 'global' initialisation.
itertools
Get familiar with this great library. It offers highly efficient solutions for many iteration problems.
From the documentation you can learn many iteration patterns. Your problem is solved by groupby().
But remember, itertools work with iterators, they may be consumed only once.
from itertools import groupby
def look_and_say(iterations):
seq = '1'
for _ in range(iterations):
lst = [str(len(list(v))) + k for k, v in groupby(seq)]
seq = "".join(lst)
return seq | {
"domain": "codereview.stackexchange",
"id": 45503,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
c++, multithreading, parsing
Title: Multithreaded natural language text parser (Rev.2)
Question: This is the second iteration of the Multithreaded natural language text parser code review. Special thanks goes to G. Sliepen who conducted the first review.
Before reading this post, please read the first iteration, since without it most of the text below doesn’t make sense.
Functional specification
Implement a multithreading parser based on existing natural language tokenizer.
Parser should compile text into sequences of lexem ids.
Parser should create structures to get lexem text by id and id by lexem text.
Lexems id must be unique for lexem, but no any other stronger requirements are provided.
Performance and memory footprint is critical, since the amount of data is huge (gigabytes).
Nice to have the approach which could be portable to GPU for further speed up.
Changes
The approach with std::async implemented; I like it more.
Functions return std::vector relying on RVO/NRVO. It helps.
G. Sliepen, thank you for your points here!
Not changed things are covered in the Answers to code review points and questions section.
The code
Fully functional runnable demo.
Please note that godbolt.org doesn’t run code with MSVC, so don’t expect to see the output.
using lexem_t = unsigned int;
struct LexemData {
lexem_t id;
std::size_t count;
};
struct LexemDataAtomic {
lexem_t id;
std::atomic<std::size_t> count;
LexemDataAtomic(unsigned int i, std::size_t count) :
id{ i },
count{ count }
{
}
LexemDataAtomic(const LexemDataAtomic& rhs) :
id{ rhs.id },
count{ rhs.count.load() }
{
}
LexemDataAtomic& operator=(const LexemDataAtomic& rhs)
{
if (&rhs != this)
{
id = rhs.id;
count = rhs.count.load();
}
}
LexemDataAtomic(LexemDataAtomic&&) = delete; // atomic is not moveable
LexemDataAtomic& operator=(LexemDataAtomic&&) = delete;
}; | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
template <typename TextBaseType>
struct CompiledText {
TextBaseType* text_base;
std::vector<lexem_t> data;
CompiledText(TextBaseType& text_base) : text_base(&text_base) {}
};
template <typename LexemsMapType, typename DictMapType>
struct TextBase {
LexemsMapType lexems_data;
DictMapType dict;
enum {
use_all_available_threads = 0,
};
};
struct TextBaseMultiThreaded
: public TextBase<Concurrency::concurrent_unordered_map<std::string, LexemDataAtomic>,
Concurrency::concurrent_unordered_map<lexem_t, Concurrency::concurrent_unordered_map<std::string, LexemDataAtomic>::iterator>>
{
CompiledText<TextBaseMultiThreaded> tokenize(std::string_view text, std::size_t threads = 0);
private:
void tokenize_chunk_to(std::vector<lexem_t>& compiled, std::string_view text, lexem_t start_id);
std::vector<lexem_t> tokenize_chunk(std::string_view text, lexem_t start_id);
};
struct TextBaseSingleThreaded
: public TextBase<std::unordered_map<std::string, LexemData>,
std::unordered_map<lexem_t, std::unordered_map<std::string, LexemData>::iterator>>
{
CompiledText<TextBaseSingleThreaded> tokenize(std::string_view text);
};
CompiledText<TextBaseSingleThreaded> TextBaseSingleThreaded::tokenize(std::string_view text)
{
CompiledText<TextBaseSingleThreaded> compiled_text(*this);
lexem_t id = 0;
for (auto lexem : TokenRange(text)) {
auto res = lexems_data.insert({ std::string(lexem), { id, 0 } });
if (res.second) {
dict[id] = res.first;
++id;
}
res.first->second.count++;
const auto code = res.first->second.id;
compiled_text.data.push_back(code);
}
return compiled_text;
}
void TextBaseMultiThreaded::tokenize_chunk_to(std::vector<lexem_t>& compiled, std::string_view text, lexem_t start_id)
{
auto id = start_id; | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
for (auto lexem : TokenRange(text)) {
auto res = lexems_data.insert({ std::string(lexem),{ id, 0} });
if (res.second) {
dict[id] = res.first;
++id;
}
++(res.first->second.count);
const auto code = res.first->second.id;
compiled.push_back(code);
}
}
std::vector<lexem_t> TextBaseMultiThreaded::tokenize_chunk(std::string_view text, lexem_t start_id)
{
std::vector<lexem_t> compiled;
auto id = start_id;
for (auto lexem : TokenRange(text)) {
auto res = lexems_data.insert({ std::string(lexem),{ id, 0} });
if (res.second) {
dict[id] = res.first;
++id;
}
++(res.first->second.count);
const auto code = res.first->second.id;
compiled.push_back(code);
}
return compiled;
}
// If n_chunks == 0, use all available threads
CompiledText<TextBaseMultiThreaded> TextBaseMultiThreaded::tokenize(std::string_view text, std::size_t n_chunks)
{
n_chunks = n_chunks != use_all_available_threads ? n_chunks : std::max((std::size_t)std::thread::hardware_concurrency(), (std::size_t)1);
std::size_t chunk_size = text.size() / n_chunks;
std::vector<std::future<std::vector<lexem_t>>> results;
results.reserve(n_chunks);
std::size_t carry = 0;
const TokenRange empty({});
auto delimiters = empty.begin().get_delimiters();
CompiledText<TextBaseMultiThreaded> compiled_text(*this);
for (std::size_t chunk = 0; chunk < n_chunks; ++chunk) {
if (carry >= chunk_size) {
carry -= chunk_size;
continue;
}
std::size_t chunk_start = chunk * chunk_size + carry;
std::size_t chunk_end = (chunk + 1) * chunk_size;
std::string_view search_range = text.substr(chunk_end - 1);
carry = search_range.find_first_of(delimiters);
if (std::string_view::npos == carry) {
carry = search_range.size();
} | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
if (std::string_view::npos == carry) {
carry = search_range.size();
}
chunk_end += carry;
results.push_back(std::async(std::launch::async, &TextBaseMultiThreaded::tokenize_chunk, this,
text.substr(chunk_start, chunk_end - chunk_start), (lexem_t)(chunk * chunk_size)));
}
for (auto& result : results) {
compiled_text.data.append_range(result.get());
}
return compiled_text;
}
Final thoughts
The main problem this approach is that in case I use Concurrency::concurrent_unordered_map during parsing, the resulting dictionary will stay in it and reading from this map is slower (in my tests about 2.24 times) than from std::unordered_map. I need to read text of lexems in some time critical parts of the system, so this would have an impact.
Of course, I can copy data from Concurrency::concurrent_unordered_map back to std::unordered_map, but since this will be sequential operation, this will almost kill all the benefit from multithreading.
I have some ideas how to mitigate and improve this, but I am still in two minds if this approach worth further research.
Maybe I should consider other structures and algorithms like:
B-trees
Heap processing (like heap sorting does)
Convolution (like with std::transform_reduce or std::ranges::fold_left) | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
Most likely, this should be done on plain structures without hash maps.
This, actually, was main question when I posted this for the first code review, if the approach correct and what approach could work better here.
So, unless I get some advice on better algorithms and data structures or figure out one myself, I have to put this research on hold, even feeling that with multicore systems like GPU this could be solved times faster than just with naïve sequential approach.
Answers to code review points and questions
On the approach and multithreading
The term “naïve” although having a special meaning in programming have a kind of connotation, which allows to assume that it is very straightforward and not optimal and there is a better well-known or at least visible approach. Posting this code and design I was eager to hear this kind of feedback to learn more about possible implementation. Could you please give a hint, what kind of approach wouldn’t be naïve?
Please note that functional specification explicitly states that amount of data expected to be huge; some of the answers below will rely on this fact and the fact that I don’t focus at the moment on some inefficiency for small texts; this could be handled, but this it not the point of the code at the moment. | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
c++, multithreading, parsing
Taking into account a huge size of data, the slowest thread shouldn’t be much slower that any other as they have almost the same amount of lexems on average; at least I don’t expect something critical. Do you see any way to improve this?
I have exactly as many threads as CPU cores which is specified in the code with the call to std::max((std::size_t)std::thread::hardware_concurrency(). Actually, I tested, reducing this number by one to give one thread to OS and other stuff, I even tried 2 times more and less threads; nothing changed dramatically, since OS and C++ Library handle threads well and unless the gap is huge, this doesn’t affect performance; nowadays applications runs dozens, even hundreds threads without dramatic impact. Of course, I am aware about switching and balance.
My chunks can’t be small by functional specification. With gigabytes of text, I would need millions of CPU cores to have small chunks.
So, to put in a nutshell, I can’t get the point you make on multithreading issues in my code.
On functional decomposition
This really hits a record. The add_to_data function will consist of one line of code and which is most important, for this I will need to return the code of the added/found lexem from add_to_dictionary function and then pass to add_to_data. I don’t care about performance because of inlining and optimizations, I care about the code structure. Is it worth to extract one line of obvious code only with a sole purpose to name it?
Just want to take a chance of asking you if you could help me with my questions posted in form of comments to Natural language text fast tokenizer (Rev.3) (as a separate code review section if you will create one). Maybe your answers to these questions will help me to get this decomposition.
On copying strings
We already discussed this in the comments for Multithreaded natural language text parser. Additionally to the fact that I will release the text buffer after processing, let me add some extra points: | {
"domain": "codereview.stackexchange",
"id": 45504,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, parsing",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.