测试函数执行效率的问题
大家一起来看看下面的2个函数,首先大家猜猜哪个函数的运行效率更高?
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
【相关文章:】
没有相关文章
【发表评论】【打印此文】【关闭窗口】【点击数: 】
