我需要的,我没有任何分析工具的情况下,类似的东西,但是我想要计算特定代码块内有多少线程以及每个线程在该代码块中花费的时间量(tick)。在这种情况下,每个块都需要一个可供所有线程访问的唯一静态变量,我需要稍后将该变量引用到incr(我在实际代码中使用了日志API而不是printf,但这也适用)。起初我还以为我是通过以下操作十分巧妙:
#define PROF_START { \
static volatile int entry_count##___FUNCTION__##__LINE__ = 0; int *ptc = &entry_count##___FUNCTION__##__LINE__; \
clock_t start, end; \
start = times(0); \
(*ptc)++;
但后来我意识到,这只是愚蠢和C编译器将只为你做这个,只要每一个“静态”的声明是其自身块:
#include <stdio.h>
#include <sys/times.h>
#define PROF_START { \
static int entry_count = 0; \
clock_t start, end; \
start = times(0); \
entry_count++;
#define PROF_END \
end = times(0); \
printf("[%s:%d] TIMER: %ld:%d\n" , __FUNCTION__, __LINE__, end-start, entry_count); \
entry_count--; \
}
请注意每个宏中的开放/关闭括号。这不是严格的线程安全的,但为了我的分析目的,我可以假设incr和decr操作是原子的。这是一个使用宏的递归示例
#define ITEM_COUNT 5
struct node {
int data;
struct node *next;
};
revsort(struct node **head)
{
struct node *current = *head;
struct node *next_item;
while (current->next)
{
PROF_START
next_item = current->next;
current->next = next_item->next;
next_item->next = *head;
*head = next_item;
PROF_END
}
}
rrevsort(struct node **head)
{
struct node *current = *head;
struct node *next_item = current->next;
PROF_START
current->next = 0;
if (next_item)
{
*head = next_item;
rrevsort(head);
next_item->next = current;
}
PROF_END
}
printnode(struct node *head)
{
if (head)
{
printf("%d ", head->data);
printnode(head->next);
}
else
printf("\n");
}
main()
{
struct node node_list[ITEM_COUNT];
struct node *head = &node_list[0];
int i;
for (i=0; i < ITEM_COUNT - 1; i++)
{
PROF_START
node_list[i].data = i;
node_list[i].next = &node_list[i+1];
PROF_END
}
node_list[i].data = i;
node_list[i].next = 0;
printf("before\n");
printnode(head);
revsort(&head);
printf("after\n");
printnode(head);
rrevsort(&head);
printf("before\n");
printnode(head);
}
额外提示,上述程序是一个常见的面试问题。摘自“nm -A”:
macro:0804a034 b entry_count.1715
macro:0804a030 b entry_count.1739
macro:0804a028 b entry_count.1768
macro:0804a02c b entry_count.1775
当然,你的意思是独特的变量名称,而不是随机的? – 2009-07-04 15:23:00
我有点困惑这将如何有用。程序员之后会使用my_variable_ *引用吗? getCurrentTime()有一些有用的副作用吗? – SingleNegationElimination 2009-07-04 18:23:53