Created
January 2, 2015 12:22
-
-
Save r-lyeh-archived/1de762acd24c51a4a3a3 to your computer and use it in GitHub Desktop.
every
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// simple every() function | |
// - rlyeh. mit licensed | |
// @todo: during, in, when, | |
#pragma once | |
#include <map> | |
#ifdef EVERY_USE_OMP | |
#include <omp.h> | |
#else | |
#include <chrono> | |
#endif | |
template<typename T> | |
bool every( float time, const char *const file, int counter ) { | |
using pair_type = std::pair<const char *const, int>; | |
static std::map< pair_type, T > map; | |
#ifdef EVERY_USE_OMP | |
T now( omp_get_wtime() ); | |
#else | |
T now( std::chrono::duration_cast<std::chrono::seconds> | |
( std::chrono::system_clock::now().time_since_epoch() ).count() ); | |
#endif | |
pair_type pair( file, counter ); | |
auto found = map.find(pair); | |
return found == map.end() ? | |
( map.insert( std::pair<pair_type,T>(pair, now) ), false ) : | |
( now - found->second >= time ? (found->second = now, true) : false ); | |
} | |
enum { | |
second = 1, | |
minute = 60 | |
}; | |
static inline float seconds( unsigned N = 1 ) { return second * N; } | |
static inline float minutes( unsigned N = 1 ) { return minute * N; } | |
#define every(time) every<double>( time, __FILE__, __COUNTER__ ) | |
/* | |
// usage | |
#include <stdlib.h> | |
#include "every.hpp" | |
int main() { | |
for(;;) { | |
if( every(1) ) puts("1!\n"); | |
if( every(5) ) puts("5!\n"); | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment