#include <stdio.h>
#define NPRINT(n, ...) do { static int __t = 0; if (__t++ >= 0) printf(__VA_ARGS__), __t = -(n)+1; } while(0)
int main() {
for (int i = 0; i < 100; ++i)
{
NPRINT(10, "10 i = %d\n", i);
}
printf("--------\n");
for (int i = 0; i < 100; ++i)
{
NPRINT(20, "20 i = %d\n", i);
}
return 0;
}
glog也有类似的宏,看一下大佬们是怎么写的
// Use macro expansion to create, for each use of LOG_EVERY_N(), static
// variables with the __LINE__ expansion as part of the variable name.
#define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
#define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
#define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
#define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
#define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
++LOG_OCCURRENCES; \
if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
if (LOG_OCCURRENCES_MOD_N == 1) \
google::LogMessage( \
__FILE__, __LINE__, google::GLOG_ ## severity, LOG_OCCURRENCES, \
&what_to_do).stream()
#define LOG_EVERY_N(severity, n) \
SOME_KIND_OF_LOG_EVERY_N(severity, (n), google::LogMessage::SendToLog)
用法
LOG_EVERY_N(INFO, 3) << "LOG_EVERY_N 3 i:" << i << " google::COUNTER:" << google::COUNTER;
因为他用的c++的流式方法,所以不能像我这样用do while形式。
为了记录当前执行次数,用宏定义了一个 occurrences_LINE
的静态变量。宏玩的很溜啊。