Loop code for a given time

Just made a C++11 lambded timed loop macro and wanted to share it somewhere in case it’s useful! And specially in case I forget!

What it does is execute something repeatedly for a given time. Based on this answer on SO.

template<typename FUNCTION>
inline void timed_loop(unsigned long long millis, FUNCTION f)
{
	unsigned long long t1 = ofGetElapsedTimeMillis();
	while(ofGetElapsedTimeMillis() - t1 < millis)
	{
		f();
	}
}

So if you want to log something for a given time…I don’t know maybe someone wants to… you can do:

timed_loop( 1000, [&]()
{
    ofLog() << "Something for a given time";
});

This will log repeatedly for a second.

This uses an anonymous lamda function and executes whatever you put inside in the while loop you see above. The & inside the brackets (capture-list) allows you to access variables in the current scope.

1 Like