I feel like I'm missing something obvious, but, is there a way to name Google Benchmark argument values?
---------------- ----------
Benchmark Benchmark
---------------- ----------
NameTest/Alex instead of NameTest/0
NameTest/Bob NameTest/1
NameTest/Charles NameTest/2
for a benchmark defined something like this:
inline constexpr auto names = std::array{ "Alex", "Bob", "Charles" };
static void NameTest(benchmark::State& state)
{
const auto name = names[state.range(0)];
}
BENCHMARK(NameTest)->DenseRange(0, names.size() - 1);
you can call SetLabel on the State object that is passed in.
Related
This is my code:
HelloApplication::HelloApplication(const Wt::WEnvironment& env)
: Wt::WApplication(env)
{
setTitle("Data Interpolation");
Wt::WText *InitialExplanation = root()->addWidget(std::make_unique<Wt::WText>());
InitialExplanation->setText("Welcome! This is a page that will allow you to interpolate the value at a point in the domain of your dataset, using other points in your dataset.\n I used Lagrange Interpolation for this calculation.\n Created By Vashist Hegde");
root()->addWidget(std::make_unique<Wt::WBreak>());
std::vector<double> xi;
std::vector<double> yi;
std::vector<double> xMissing;
double xM;
auto addDataPoint = [this,xi,yi,lineEdit1,lineEdit2] () mutable{
/// neither of the following push_backs is working.
/// I get 2 empty vectors in the end.
xi.push_back(std::move(std::stod(lineEdit1->text())));
yi.push_back(std::move(std::stod(lineEdit2->text())));
xi.push_back(3.5);
yi.push_back(4.5);
};
I don't get any errors but when I run the program, the vectors are just not getting populated. I get 0 sized vectors.
Is this related to my general C++ usage or is it related to Wt (C++ Web toolkit)?
If it is related to the general C++ usage, please help me as to what I'm doing wrong.
Your lambda should capture the variable by ref which has to be to be modified, otherwise the changes will be done to the copy of the captured things.
Additionally, you need to invoke lambda for get in action.
auto addDataPoint = [this,&xi,&yi,lineEdit1,lineEdit2] () mutable {
// ...... do something
};
addDataPoint(); // call lambda
alternatively pass them as ref qualified arguments
auto addDataPoint = [this, lineEdit1,lineEdit2]
(auto& xi_para, auto &yi_para,) mutable {
// ...... do something
};
addDataPoint(xi, yi); // call lambda with args
````
I have a special class to be used as return type of methods, containing the wanted value or in case of failure an error message which is even cascading from earlier errors. It works as expected.
As the returned type is differently complex I like to use the keyword auto. But when using a lot of methods I have to create new return variables.
A typical part of code looks like this:
auto ret1 = methodA();
if(ret1.isValid()...
auto ret2 = methodB();
if(ret2.isValid()...
I dont like to always create a new variable. But I like the elegant way of error handling. Using a more dump return type like an error code in integer would solve the problem but then I have no benefit from the error handling return type.
Is there any trick to reuse the first return variable ret1?
You would have to create new scopes to reuse the variable name for a different variable, like:
{
auto ret = methodA();
if (ret.isValid()) ...
}
{
auto ret = methodB();
if (ret.isValid()) ...
}
You can also take advantage of the scope created by if, placing the init-statement inside:
if (auto ret = methodA(); ret.isValid()) ...
if (auto ret = methodB(); ret.isValid()) ...
auto is not a type.
It is a keyword, that says "put the type here for me, by deducing it from the initial value". That occurs during compilation, once.
You cannot reuse ret1 to store an object of a different type, whether you use auto or not.
This shouldn't really be a problem. If you're concerned about "running out of names", or "having many similar names", your names are not descriptive enough and/or your scopes aren't tight enough.
auto is not a type. In auto foo = bar(); the compiler simply figures out what type bar() actually returns and substitutes that in. So if bar() returns int then that's the type of foo, if it returns bool then that is the type of foo. And once the type that auto should be replaced with (the first time) has been determined, then it can never change. auto doesn't mean "variable type" it just means "hey compiler, I'm too lazy to figure out the type to put here, please do it for me", but there is no difference what-so-ever compared to you just writing the final type yourself.
So, you can reuse the variable if what you assign to it the second time is of the same type as the first time - otherwise not.
I dont like to always create a new variable.
Much better is to create a const variable:
const auto ret1 = methodA();
if(ret1.isValid()...
const auto ret2 = methodB();
if(ret2.isValid()...
In this case you need to make const all the methods like isValid, but that is even better: "is" shouldn't have side effects and modify the state.
Next step is to remove the temp variable at all:
if(methodA().isValid()) {
...
}
if(methodB().isValid()) {
...
}
The alternative is to wrap each function call into a block:
{
const auto ret = methodA();
if(ret.isValid()...
}
{
const auto ret = methodB();
if(ret.isValid()...
}
This allows you to reuse the const variable name.
Each block becomes a candidate for extraction into a separate function (see Uncle Bob in "Clean Code").
Why is this reporting error: no matching function for call to ‘as<Eigen::Matrix<double, 400, 1, 0, 400, 1> >(int)’ and cannot convert ‘3’ (type ‘int’) to type ‘SEXP {aka SEXPREC*}’? There appears to be a similar problem here.
In a previous question, I asked about registering plugins so that I could use a c++ template library from within R. Continuing on with that example, I still cannot get this small example to work. The plugin issue has been figured out, but now Rcpp::as won't allow me to convert numeric vectors and matrices from R into the appropriate c++ type.
library(Rcpp)
inc <-
'template <size_t dim>
class SillyWrapper
{
public:
Eigen::Matrix<double,dim,1> m_vec;
SillyWrapper(const Eigen::Matrix<int,dim,1>& vec) : m_vec(vec) {};
void printData() { Rcpp::Rcout << m_vec(0); };
};'
src <- '
void foo(){
const int dim = 400;
SillyWrapper<dim> myThing(Rcpp::as<Eigen::Map<Eigen::Matrix<double,dim,1>>>(3));
myThing.printData();
}'
f <- function(x){
plug <- Rcpp.plugin.maker(include.before = "#include <Eigen/Dense>")
settings <- plug()
settings$env$PKG_CPPFLAGS = "-I/usr/include/eigen3"
settings
}
Rcpp::registerPlugin(name = "Eigen3", plugin = f)
fun <- cppFunction(code = src,
plugins = "Eigen3",
includes = inc)
A few other things:
I am registering my own plugin instead of using RcppEigen for practice (perhaps it will help later when I need to use other header only libraries). I plan on relying on plugins because I have a lot of header files I need to include, and I don't want to paste them all together and assign the massive string to inc above.
I cannot use Eigen::MatrixXd I need to size the matrices with the compiler.
#DirkEddelbuettel mentioned something about configure logic. I tried searching that, but no luck.
I’m trying to JIT compile some functions in an existing C/C++ program at runtime, but I’m running into some trouble with global variable initialization. Specifically, the approach I’ve taken is to use Clang to precompile the program into IR bitcode modules in addition to the executable. At runtime, the program loads the modules, transforms them (program specialization), compiles and executes them. As it turns out, I have some global variables that get initialized and modified during execution of the “host” program. Currently, these globals are also getting initialized in the JIT compiled code, whereas I’d like them to be mapped to the host global variables instead. Can someone help me with this?
A small repro is excerpted below. Full source code is here. The file somefunc.cpp gets precompiled during build, and is loaded in the main() function in testCompile.cpp. The global variable xyz is initialized to point to 25 in somefunc.cpp, but I’d like it to point to 10 as in main() instead. In other words, the assertion in main() should succeed.
I tried a few different ways to solve this problem. The ChangeGlobal() function attempts (unsuccessfully) to achieve this updateGlobalMapping(). The second, more hacky approach uses a new global variable initialized appropriately. I can get this latter approach to work for some types of globals, but is there a more elegant approach than this?
//————— somefunc.h ————————
extern int *xyz;
//—————— somefunc.cpp ——————
int abc = 25;
int *xyz = &abc;
int somefunc() {
return *xyz;
}
//—————— testCompile.cpp ——————
class JitCompiler {
public:
JitCompiler(const std::string module_file);
void LoadModule(const std::string& file);
template <typename FnType>
FnType CompileFunc(FnType fn, const std::string& fn_name);
void ChangeGlobal();
private:
std::unique_ptr<LLVMContext> context_;
Module *module_;
std::unique_ptr<ExecutionEngine> engine_;
};
void JitCompiler::ChangeGlobal() {
// ----------------- #1: UpdateGlobalMapping -----------------
//auto g = engine_->FindGlobalVariableNamed("xyz");
//engine_->updateGlobalMapping(g, &xyz);
//assert(engine_->getGlobalValueAddress("xyz") == (uint64_t) &xyz);
// ----------------- #2: Replace with new global ————————
// ------- Ugly hack that works for globals of type T** ----------
auto g = engine_->FindGlobalVariableNamed("xyz");
Constant *addr_i = ConstantInt::get(*context_, APInt(64, (uint64_t) xyz));
auto addr = ConstantExpr::getIntToPtr(
addr_i, g->getType()->getPointerElementType());
GlobalVariable *n = new GlobalVariable(
*module_,
g->getType()->getPointerElementType(),
g->isConstant(),
g->getLinkage(),
addr,
g->getName() + "_new");
g->replaceAllUsesWith(n);
n->takeName(g);
g->eraseFromParent();
}
int main() {
xyz = new int (10);
JitCompiler jit("somefunc.bc");
jit.ChangeGlobal();
auto fn = jit.CompileFunc(&somefunc, "somefunc");
assert(somefunc() == fn());
}
A better approach is the combination of the two you presented, that is, to create a new global with external linkage mapped to &xyz and substitute it for the original:
auto g = engine_->FindGlobalVariableNamed("xyz");
GlobalVariable *n = new GlobalVariable(
g->getType()->getPointerElementType(),
g->isConstant(),
ExternalLinkage
nullptr,
g->getName() + "_new");
engine_->updateGlobalMapping(n, &xyz);
g->replaceAllUsesWith(n);
n->takeName(g);
g->eraseFromParent();
I am required to create a data structure and I have so far created a simple table consisting of 4 different vectors that represent variable. variable type, bool result and PKB output. I know that it is not the best way to do it but I was planning to insert and retrieve using index. However, I encounter a problem with Query ID because I am expecting to use getMethods to retrieve the information. I need to find a way to retrieve the information much more smoothly than to run through by index. The retrieval process will be by batch of Query ID.
I am new to Cplusplus and I am not sure what data structure or how I can solve it. I am not expecting a direct answer but a suggestion would suffice. Names that I probably never heard before. It would be best if you have a step by step guide.
---Query ID ---- Variable --- Variable Type --- bool result---- PKB output
---- 1 ------------------- x ----- assignment ----------- true ----------- null
------------------------------------------------- 1 ------------------- w ---------- while -------------- false ---------- null
------------------------------------------------- 1 ------------------ ifstat----------- if ------------- ----false ---- ----- null
------------------------------------------------ 2 ------------------- x ------ assignment ----------- false ---------- null --------------------------------------------
From what I understand reading your question, You can use a std::multimap using int and struct. For instance
// C++11 for nullptr
#include <string>
#include <map>
struct Data {
std::string variable;
std::string variableType;
bool result;
PKB output; // I suppose PKB is an already defined type
Data(std::string var, std::string varType, bool res = false, PKB out = nullptr) :
variable(var), variableType(varType), result(res), output(out) {}
inline bool operator <(const Data & rhs) {
. . . // Add your own comparison logic
}
};
std::multimap<int, Data> myMap;
myMap.insert((1, Data("x", "assignment", true)));
myMap.insert((1, Data("w", "while")));
myMap.insert((1, Data("ifstat", "if")));
myMap.insert((2, Data("x", "assignment")));
I don't think I understand the question completely. But I think your using the standard library that contains the def of a vector, meaning you would have to use the getters and setters of that std. I would just make a function with a quick search algorithm that uses the getter already defined in the vector.