今天遇到这样一个问题,
int a,b;sum=0;
//a,b,赋值
//...
//当a << b 时,下面2个函数哪个更快?
void fun1(){
for(int i=0;i<a;i++){
for(int j=0;j<b;j++){
sum++;
}
}
}
void fun2(){
for(int i=0;i<b;i++){
for(int j=0;j<a;j++){
sum++;
}
}
}
咋一看,当a 远小于 b 时,fun2应该更快一点吧,fun2 内循环 与外循环的切换要少一些,从堆栈退出的次数要少很多。这只是感觉,于是我又写了如下程序做了一个测试:
using System;
using System.Threading; 



class Class1
{
static uint a = 100000000;
static uint b = 10;
static Thread th1;
static Thread th2; 
[STAThread] 
static void Main(string[] args)
{
th1 = new Thread(new ThreadStart(foo1));
th2 = new Thread(new ThreadStart(foo2));
th1.Start();
th2.Start();
} 



static void foo1()
{
uint i = 0;
uint j = 0;
uint sum = 0; 
for(i=0; i<a; i++)
{ 
for(j=0;j<b;j++)
{
sum=sum+1;
}
}
Console.WriteLine("foo1 Over");
} 



static void foo2()
{
uint sum = 0; 
for(uint i=0; i<b; i++)
{ 
for(uint j=0;j<a;j++)
{
sum += 1;
}
}
Console.WriteLine("foo2 Over");
}
} 


运行结果如下:
foo2 Over
foo1 Over
博主遇到一个问题,当a远小于b时,探讨fun1和fun2两个函数哪个执行更快。初步感觉fun2更快,因其内、外循环切换及从堆栈退出次数少,随后博主编写程序进行了测试。
3万+

被折叠的 条评论
为什么被折叠?



