我需要的,我沒有任何分析工具的情況下,類似的東西,但是我想要計算特定代碼塊內有多少線程以及每個線程在該代碼塊中花費的時間量(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