How can I measure the time taken to execute a function call in ATS? - ats

Say I wrote a function foo and I would like to find out the time taken to execute foo(1000). Is there already a package available for doing this?

If seconds-resolution is OK, you can #include "libats/libc/DATS/time.dats" and then use time() and difftime():
implement main0() = {
val before = time()
val _ = foo(1000)
val () = println!(difftime(time(), before))
}
If you'd like finer resolution you can, under Linux, use libc's gettimeofday():
extern fun reset_timer(): void = "ext#reset_timer"
extern fun elapsed_time(): double = "ext#elapsed_time"
%{
#include <sys/time.h>
#include <time.h>
struct timeval timer_timeval;
void reset_timer() { gettimeofday(&timer_timeval, NULL); }
double elapsed_time() {
struct timeval now;
gettimeofday(&now, NULL);
int secs = now.tv_sec - timer_timeval.tv_sec;
double ms = (now.tv_usec - timer_timeval.tv_usec) / ((double)1000000);
return(secs + ms);
}
%}
/* OCaml-style helper to ignore the value of foo(1000) */
fn {a:t#ype} ignore(x: a): void = ()
implement main0() =
begin
reset_timer();
ignore(foo(1000));
println!("foo(1000) took: ", elapsed_time(), "s");
end
Output (where foo(1000) takes about 3000.3 milliseconds):
foo(1000) took: 3.000296s

Related

Composing boost::variant visitors for recursive variants

I have an application with several boost::variants which share many of the fields. I would like to be able to compose these visitors into visitors for "larger" variants without copying and pasting a bunch of code. It seems straightforward to do this for non-recursive variants, but once you have a recursive one, the self-references within the visitor (of course) point to the wrong class. To make this concrete (and cribbing from the boost::variant docs):
#include "boost/variant.hpp"
#include <iostream>
struct add;
struct sub;
template <typename OpTag> struct binop;
typedef boost::variant<
int
, boost::recursive_wrapper< binop<add> >
, boost::recursive_wrapper< binop<sub> >
> expression;
template <typename OpTag>
struct binop
{
expression left;
expression right;
binop( const expression & lhs, const expression & rhs )
: left(lhs), right(rhs)
{
}
};
// Add multiplication
struct mult;
typedef boost::variant<
int
, boost::recursive_wrapper< binop<add> >
, boost::recursive_wrapper< binop<sub> >
, boost::recursive_wrapper< binop<mult> >
> mult_expression;
class calculator : public boost::static_visitor<int>
{
public:
int operator()(int value) const
{
return value;
}
int operator()(const binop<add> & binary) const
{
return boost::apply_visitor( *this, binary.left )
+ boost::apply_visitor( *this, binary.right );
}
int operator()(const binop<sub> & binary) const
{
return boost::apply_visitor( *this, binary.left )
- boost::apply_visitor( *this, binary.right );
}
};
class mult_calculator : public boost::static_visitor<int>
{
public:
int operator()(int value) const
{
return value;
}
int operator()(const binop<add> & binary) const
{
return boost::apply_visitor( *this, binary.left )
+ boost::apply_visitor( *this, binary.right );
}
int operator()(const binop<sub> & binary) const
{
return boost::apply_visitor( *this, binary.left )
- boost::apply_visitor( *this, binary.right );
}
int operator()(const binop<mult> & binary) const
{
return boost::apply_visitor( *this, binary.left )
* boost::apply_visitor( *this, binary.right );
}
};
// I'd like something like this to compile
// class better_mult_calculator : public calculator
// {
// public:
// int operator()(const binop<mult> & binary) const
// {
// return boost::apply_visitor( *this, binary.left )
// * boost::apply_visitor( *this, binary.right );
// }
// };
int main(int argc, char **argv)
{
// result = ((7-3)+8) = 12
expression result(binop<add>(binop<sub>(7,3), 8));
assert( boost::apply_visitor(calculator(),result) == 12 );
std::cout << "Success add" << std::endl;
// result2 = ((7-3)+8)*2 = 12
mult_expression result2(binop<mult>(binop<add>(binop<sub>(7,3), 8),2));
assert( boost::apply_visitor(mult_calculator(),result2) == 24 );
std::cout << "Success mult" << std::endl;
}
I would really like something like that commented out better_mult_expression to compile (and work) but it doesn't -- because the this pointers within the base calculator visitor don't reference mult_expression, but expression.
Does anyone have suggestions for overcoming this or am I just barking down the wrong tree?
Firstly, I'd suggest the variant to include all possible node types, not distinguishing between mult and expression. This distinction makes no sense at the AST level, only at a parser stage (if you implement operator precedence in recursive/PEG fashion).
Other than that, here's a few observations:
if you encapsulate the apply_visitor dispatch into your evaluation functor you can reduce the code duplication by a big factor
your real question seems not to be about composing variants, but composing visitors, more specifically, by inheritance.
You can use using to pull inherited overloads into scope for overload resolution, so this might be the most direct answer:
Live On Coliru
struct better_mult_calculator : calculator {
using calculator::operator();
auto operator()(const binop<mult>& binary) const
{
return boost::apply_visitor(*this, binary.left) *
boost::apply_visitor(*this, binary.right);
}
};
IMPROVING!
Starting from that listing let's shave off some noise!
remove unncessary AST distinction (-40 lines, down to 55 lines of code)
generalize the operations; the <functional> header comes standard with these:
namespace AST {
template <typename> struct binop;
using add = binop<std::plus<>>;
using sub = binop<std::minus<>>;
using mult = binop<std::multiplies<>>;
using expr = boost::variant<int,
recursive_wrapper<add>,
recursive_wrapper<sub>,
recursive_wrapper<mult>>;
template <typename> struct binop { expr left, right; };
} // namespace AST
Now the entire calculator can be:
struct calculator : boost::static_visitor<int> {
int operator()(int value) const { return value; }
template <typename Op>
int operator()(AST::binop<Op> const& binary) const {
return Op{}(boost::apply_visitor(*this, binary.left),
boost::apply_visitor(*this, binary.right));
}
};
Here your variant can add arbitrary operations without even needing to touch the calculator.
Live Demo, 43 Lines Of Code
Like I mentioned starting off, encapsulate visitation!
struct Calculator {
template <typename... T> int operator()(boost::variant<T...> const& v) const {
return boost::apply_visitor(*this, v);
}
template <typename T>
int operator()(T const& lit) const { return lit; }
template <typename Op>
int operator()(AST::binop<Op> const& bin) const {
return Op{}(operator()(bin.left), operator()(bin.right));
}
};
Now you can just call your calculator, like intended:
Calculator calc;
auto result1 = calc(e1);
It will work when you extend the variant with operatios or even other literal types (like e.g. double). It will even work, regardless of whether you pass it an incompatible variant type that holds a subset of the node types.
To finish that off for maintainability/readability, I'd suggest making operator() only a dispatch function:
Full Demo
Live On Coliru
#include <boost/variant.hpp>
#include <iostream>
namespace AST {
using boost::recursive_wrapper;
template <typename> struct binop;
using add = binop<std::plus<>>;
using sub = binop<std::minus<>>;
using mult = binop<std::multiplies<>>;
using expr = boost::variant<int,
recursive_wrapper<add>,
recursive_wrapper<sub>,
recursive_wrapper<mult>>;
template <typename> struct binop { expr left, right; };
} // namespace AST
struct Calculator {
auto operator()(auto const& v) const { return call(v); }
private:
template <typename... T> int call(boost::variant<T...> const& v) const {
return boost::apply_visitor(*this, v);
}
template <typename T>
int call(T const& lit) const { return lit; }
template <typename Op>
int call(AST::binop<Op> const& bin) const {
return Op{}(call(bin.left), call(bin.right));
}
};
int main()
{
using namespace AST;
std::cout << std::boolalpha;
auto sub_expr = add{sub{7, 3}, 8};
expr e1 = sub_expr;
expr e2 = mult{sub_expr, 2};
Calculator calc;
auto result1 = calc(e1);
std::cout << "result1: " << result1 << " Success? " << (12 == result1) << "\n";
// result2 = ((7-3)+8)*2 = 12
auto result2 = calc(e2);
std::cout << "result2: " << result2 << " Success? " << (24 == result2) << "\n";
}
Still prints
result1: 12 Success? true
result2: 24 Success? true

Casting vtkSmartPointer to an Inherited Class

How do I cast a vtkSmartPointer<T> to an inherited class while maintaining reference counting?
Minimal illustration:
#include <iostream>
#include <vtkSmartPointer.h>
class A: public vtkObjectBase {
public :
A(){}
static A * New(){return new A();}
int var1 = 8;
};
class B: public A {
public :
B(){}
static B * New() {return new B();}
int var2 = 12;
};
int main (int argc, char ** argv) {
vtkSmartPointer<B> b = vtkSmartPointer<B>::New();
vtkSmartPointer<A> a = b; // this is fine
std::cout << "var1 = " << a->var1 << std::endl;
// this is not fine and I cannot find a vtk equivalent
// to boost's dynamic_pointer_cast for similar functionality
// vtkSmartPointer<B> c = a; // how do I do this?
}
I'm assuming there must be a macro somewhere similar to boost's dynamic_pointer_cast<T> but I can't find it. If there isn't, and someone can suggest a method to accomplish this, I would be very grateful.
There are a couple of problems here.
In most cases you want to inherit from vtkObject, not vtkObjectBase.
You are missing vtkTypeMacro().
What you are looking for is T::SafeDownCast().
So your code would become:
#include <vtkSmartPointer.h>
class A : public vtkObject {
public :
vtkTypeMacro(A, vtkObject);
A() = default;
static A* New() { return new A(); }
int var1 = 8;
};
class B : public A {
public:
vtkTypeMacro(B, A);
B() = default;
static B* New() { return new B(); }
int var2 = 12;
};
int main (int argc, char ** argv) {
vtkSmartPointer<B> b = vtkSmartPointer<B>::New();
vtkSmartPointer<A> a = b;
vtkSmartPointer<B> c = B::SafeDownCast(a);
}
For more information, please, consult VTK User Guide, chapter "14.6 Writing A VTK Class".
Okay nevermind, I found an answer that appears to work. I'll post it in case someone stumbles across here and wants to avoid the frustration I had.
It turns out that reference counting happens in the vtkObjectBase. So as long as code inherits from that, vtk will keep an accurate count. Thankfully vtk won't let you use vtkSmartPointer unless it does.
So it would seem that to implement a boost style macro one could simply do the following:
template<typename T,typename V> vtkSmartPointer<T> vtkDynamicPointerCast(vtkSmartPointer<V> src) {
T* v = dynamic_cast<T*>(src.Get());
if (v) return vtkSmartPointer<T>(v);
else return vtkSmartPointer<T>();
}

How can I use std::result_of to return the function type instead of void

I am trying to get the return type of a function that I bind in. In this instance I was expecting to see the return type of GetFactorialResult (int).
#include <iostream>
#include <boost/core/demangle.hpp>
#include <typeinfo>
namespace
{
const int testNumber = 10;
int GetFactorialResult(int number)
{
if (number > 1)
{
return number * GetFactorialResult(number - 1);
}
else
{
return 1;
}
}
template <typename Func, typename... Args>
void Submit(Func&& func, Args&&... args)
{
auto boundTask = std::bind(std::forward<Func>(func), std::forward<Args>(args)...);
using ResultType = typename std::result_of<decltype(boundTask)()>::type;
char const * name = typeid( ResultType ).name();
std::cout << boost::core::demangle( name ) << std::endl;
}
}
int main()
{
Submit([](int number)
{
GetFactorialResult(number);
}, number);
return 0;
}
Output
void
0
When I print the type of boundTask, I see what I expect:
std::_Bind<\main::{lambda(int)#1} (int)> (the backslash doesnt
exist, but couldnt figure out how to display it without it).
I assume I am getting void because of I'm doing decltype(boundTask)(), but if I remove the parenthesis, it fails to compile.
I only have access to c++11 features.

C++ pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug

I keep getting this error. I know what function causes it, but don't know how to fix it. Looking up online from this post saying:
You need to pass a pointer to a dynamically allocated object, or make your own insde your chainLink class.
However, as I try to pass a string pointer. error still popping up. Here is my code.
#include <iostream>
#include "MWTNode.h"
#include "MWT.h"
using namespace std;
int main() {
MWT t;
string str ="abc";
string* strPtr = &str;
t.insert(strPtr);
std::cout << "Hello, World!" << std::endl;
return 0;
}
#include "MWTNode.h"
class MWT {
public:
MWTNode *root;
string find(const string &);
void insert(const string* string);
};
void MWT::insert(const string* word) {
MWTNode* curr = root;
MWTNode newNode;
string w = *word;
for (int i = 0; i < word->length(); i++) {
const char c = w[i];
if (curr->children.find(c) == curr->children.end()){
//curr->children[c]= MWTNode();
//node->frequency=node->frequency+1;
}
curr = &(curr->children[c]);
}
curr->flag = true;
}
#include <unordered_map>
#include <vector>
#include <string>
#include <sstream>
#include <set>
using namespace std;
class MWTNode {
public:
unordered_map<char, MWTNode> children;
string value;
bool flag;
int frequency;
MWTNode(const string &);
MWTNode(const char c);
MWTNode();
void setFrequency ();
int getFrequency ();
};
MWTNode::MWTNode(const string &val) {
value = val;
flag = false;
frequency = 0;
}
MWTNode::MWTNode(const char c) {
value =c;
flag = false;
frequency = 0;
}
MWTNode::MWTNode() {
value ="";
flag = false;
frequency = 0;
}
Lets highlight a few lines of the code you show
class MWT {
public:
MWTNode *root;
// ...
};
In that you declare the member variable root as a pointer.
void MWT::insert(const string* word) {
MWTNode* curr = root;
// ...
}
In the above you make curr point to where root is pointing.
But you never make root point anywhere! The MWT::root variable is uninitialized and will have an indeterminate value. Using this pointer in any way without initialization will lead to undefined behavior.
And yes you use this pointer, as you dereference curr inside the MWT::insert function.
It's a little unclear what you're doing (to me) but you need to make sure that root (and therefore curr) is a valid pointer before attempting to dereference it.

Unmanaged to managed callback much slower when target is in another AppDomain

I'm calling managed code from unmanaged code using a delegate. When I call into managed code in the default AppDomain I'm measuring an average of 5.4ns per call. When I calling to a second AppDomain I'm measuring 194ns per call. (default VS2017 x86 release configuration, not running under the debugger).
Why is performance so much lower when calling into an AppDomain that isn't the default? Since I'm coming from the unmanaged side, which has no knowledge of AppDomains I would expect to be calling straight into the target domain. However, the performance hit would imply that the delegate is calling into the default domain then marshaling to the real target. I do see UM2MDoADCallBack when stepping through the disassembly. Which shows up under WrongAppDomain: in UMThunkStub.asm
How can I prevent this unnecessary marshaling and call directly into a specific AppDomain?
The code I'm using to test this is below.
#pragma unmanaged
#include <wtypes.h>
#include <cstdint>
#include <cwchar>
typedef void (__stdcall *ManagedUpdatePtr)();
struct ProfileSample
{
static uint64_t frequency;
uint64_t startTick;
wchar_t* name;
int count;
ProfileSample(wchar_t* name_, int count_)
{
name = name_;
count = count_;
LARGE_INTEGER win32_startTick;
QueryPerformanceCounter(&win32_startTick);
startTick = win32_startTick.QuadPart;
}
~ProfileSample()
{
LARGE_INTEGER win32_endTick;
QueryPerformanceCounter(&win32_endTick);
uint64_t endTick = win32_endTick.QuadPart;
uint64_t deltaTicks = endTick - startTick;
double nanoseconds = (double) deltaTicks / (double) frequency * 1000000000.0 / count;
wchar_t buffer[128];
swprintf(buffer, _countof(buffer), L"%s - %.4f ns\n", name, nanoseconds);
OutputDebugStringW(buffer);
if (!IsDebuggerPresent())
MessageBoxW(nullptr, buffer, nullptr, 0);
}
};
uint64_t ProfileSample::frequency = 0;
int CALLBACK
WinMain(HINSTANCE, HINSTANCE, PSTR, INT)
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
ProfileSample::frequency = frequency.QuadPart;
ManagedUpdatePtr GetManagedUpdatePtr();
auto managedUpdate = GetManagedUpdatePtr();
//Warm stuff up
for ( size_t i = 0; i < 100; i++ )
managedUpdate();
const int num = 10000000;
{
ProfileSample p(L"ManagedUpdate", num);
for ( size_t i = 0; i < num; i++ )
managedUpdate();
}
return 0;
}
#pragma managed
using namespace System;
using namespace System::Diagnostics;
using namespace System::Runtime::InteropServices;
ref struct ManagedObject : MarshalByRefObject
{
ManagedUpdatePtr
GetManagedUpdatePtr()
{
auto delegate = gcnew Action(this, &ManagedObject::ManagedUpdate);
IntPtr fPtr = Marshal::GetFunctionPointerForDelegate(delegate);
return (ManagedUpdatePtr) fPtr.ToPointer();
}
void ManagedUpdate()
{
//Debug::WriteLine("\n\nManagedUpdate ({0})", (Object^) AppDomain::CurrentDomain->FriendlyName);
}
};
ManagedUpdatePtr
GetManagedUpdatePtr()
{
auto pluginDomain = AppDomain::CreateDomain("Plugin Domain");
auto managedObject = (ManagedObject^) pluginDomain->CreateInstanceAndUnwrap("ManagedHelper", "ManagedObject");
return managedObject->GetManagedUpdatePtr();
}

Resources