gpt4 book ai didi

c - 应该更慢,但更快。为什么?

转载 作者:行者123 更新时间:2023-11-30 16:02:08 25 4
gpt4 key购买 nike

好吧,让我解释一下这一点。在数组 SL[] 中,我得到了指向列表的指针(我可以说列表被分成了小部分)。所以我去 SL[0] 探索列表,然后去 SL[1] 探索列表......

typedef struct TSL {
struct TSL *next;
int a;
} LSL;

LSL* SL[n] = {0}; // Array of pointers ;)

// Loop 1
void Find_All_Arc_SL()
{
int i;
LSL *tmp;
for(i=0;i<n;i++)
{
tmp = SL[i];
while(tmp != 0)
{
//printf("I find arc! %d -> %d",i,tmp->a);
tmp = tmp -> next;
}
}
}

循环 2。

typedef struct TAL {
struct TAL *next;
int v;
int a;
} LAL;
LAL *AL = 0;

void Find_All_Arc_AL()
{

LAL *tmp;
tmp = AL;

while(tmp != 0)
{
//printf("I find arc %d -> %d \n",tmp->v,tmp->a);
tmp = tmp -> next;
};

}

在这个函数中,我只是探索列表...只需在没有任何数组等的情况下进行即可。

我的问题是:为什么 Find_All_Arc_SL() 总是比 Find_All_Arc_AL() 更快(毫秒)?这些函数的工作原理几乎相同,但第一个(更快的函数)必须做额外的工作

您要求提供完整代码。这是:你可以增加/减少n

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define n 5500

//Define struct
typedef struct TSL {
struct TSL *next;
int a;
} LSL;


typedef struct TAL {
struct TAL *next;
int v;
int a;
} LAL;


// Poiner and array of pointers
LAL *AL = 0;
LSL* SL[n] = {0};

// To Calculate time
__int64 freq, start, end, diff;


// Build graph
void Create_AL()
{

LAL *tmp;
int p,k;

for(p=0;p<n;p++)
for(k=0;k<n;k++)
{
// Add arc
tmp = malloc (sizeof(LAL));
tmp->v = p;
tmp->a = k;

if(AL == 0) { tmp->next = 0; AL = tmp; }
else { tmp->next = AL; AL = tmp; }
}
}

// Find arc
void Find_All_Arc_AL()
{

LAL *tmp;
tmp = AL;

while(tmp != 0)
{
//printf("I found arc %d -> %d \n",tmp->v,tmp->a);
tmp = tmp -> next;
};

}


// Build graph
void Create_SL()
{

LSL *tmp;
int p,k;

for(p=0;p<n;p++)
for(k=0;k<n;k++)
{
// Add arc
tmp = malloc(sizeof(LSL));
tmp -> a = k;

if(SL[p] == 0) { tmp -> next = 0; SL[p] = tmp; }
else { tmp -> next = SL[p]; SL[p] = tmp; }
}

}


void Find_All_Arc_SL()
{

int i;
LSL *tmp;


for(i=0;i<n;i++)
{
tmp = SL[i];

while(tmp != 0)
{
//printf("I find arc %d -> %d \n", i, tmp->a);
tmp = tmp -> next;
}

}

}


/**
** CALCULATE TIME!
**/

void start_timer()
{
freq = 0; start = 0; end = 0; diff = 0;

QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
QueryPerformanceCounter((LARGE_INTEGER*)&start);

}

void end_timer()
{

QueryPerformanceCounter((LARGE_INTEGER*)&end);
diff = ((end - start) * 1000) / freq;

}

int main(int argc, char *argv[])
{

Create_SL();

start_timer();
Find_All_Arc_SL();
end_timer();
printf("Find_All_Arc_SL SEARCHING ALL ARC TOOK %d \n",diff);



Create_AL();

start_timer();
Find_All_Arc_AL();
end_timer();
printf("Find_All_Arc_AL SEARCHING ALL ARC TOOK %d \n",diff);



system("PAUSE");
return 0;
}

最佳答案

这取决于您的数据。您应该发布一个完整的(工作)示例。

另外,你是如何测量时间的?您确定比较有意义吗?

关于c - 应该更慢,但更快。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5688426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com