比较Rust的“并发”与D的“并行” 运算能力,Rust 1.0 alpha2 ,D(dmd 2.066.1 LDC 0.15.1 (LLVM3.6 MS VC64)。都设置为使用总CPU数的75%.
比较2点:1、使用内存,2、运行时长。
(注:虽然此题已在 以下两篇文章中以“数学公式”法做过比较,但对运行效率的比较意义不大。
http://blog.csdn.net/iilovetopview/article/details/43745059
http://blog.csdn.net/iilovetopview/article/details/43913027
)
/*题目:
有一个整数n,写一个函数f(n),返回0到n之间出现的"1"的个数。
比如f(13)=6,现在f(1)=1,问下一个最大的f(n)=n的n是什么?
*/
一、用穷举法查10万以内的数。1、Rust:
use std::time::duration::Duration;
use std::sync::TaskPool;
use std::sync::mpsc::channel;
fn main() {
println!("(Rust Language) Please wait for some minutes,will found Next Fn(n) = n ,the n is:");
let r = Duration::span(tr);
println!(" time :{} seconds",r.num_seconds());
}
fn tr()
{
let pool = TaskPool::new(3);
let ( tx, rx) = channel();
let (mut n,max)= (1,100_000);
while(n<max)
{
let tx = tx.clone();
pool.execute(move|| {
tx.send(fnx(n)).unwrap();
});
n+=5000;
}
for a in rx.iter(){
if(a > max)
{
println!(" Now End {}",a);
break;
}
}
}
fn fnx(x:usize) -> usize
{
let ( mut pos,mut n ,mut count)=(0,x,0);
while(n >0)
{
pos = Fx(n);
if(n == pos)
{
count +=1;
println!("n is: {0}, Fn(n) is:{1} ",n,pos);
if(count >1) {break;}
}
n+=1;
if(n >x+5000){break;}
}
return n;
}
fn Fx (n: usize) -> usize
{
let mut total =0;
for i in 0..n+1{
total += Count(i);
}
return total;
}
fn Count(n: usize) ->usize
{
let (mut num,mut t) = (0,n);
while(t >= 1)
{
if(t%10 ==1){num +=1;}
t /= 10;
}
return num;
}
-------Debug
内存占用:
运行时长:
----Release
内存占用:
运行时长:
D语言(并行模式):
module fn;
import std.stdio;
import std.array;
import std.datetime;
import std.parallelism;
int[] v;
void main()
{
writeln("(D Language) Please wait for some minutes,will found Next Fn(n) = n ,the n is:");
int n=1;
while(n<100_000)
{
v~=n;
n+=5000;
}
StopWatch sw;
sw.start();
auto tp = new TaskPool(2);
foreach(c; tp.parallel(v))
{
fx(c);
}
tp.finish();
sw.stop();
writeln(" time :" , sw.peek().msecs/1000.0,"secs");
writeln(n," stop");
}
int fx(int n)
{
int count,pos,nmax = n+5000;
while(n < nmax)
{
pos = Fn(n);
if(n == pos)
{
count++;
writeln("n is: ",n, " Fn(n) is: ",pos);
if(count >1) break;
}
n++;
}
return n;
}
int Fn(int n)
{
int total;
for(int i=0;i<=n;i++)
{
total += Count(i);
}
return total;
}
int Count(int n)
{
int num;
for(int t = n;t >=1;t=t/10)
{
if(t%10 == 1) num++;
}
return num;
}
---dmd debug
内存占用:
运行时长:
-----ldc2 release
内存占用:
运行时长:
D语言(并发模式):(未完,)
--------------------待续-----------------------
大家可以看到:同样是运用3个内核(75%),D的占用内存稍大,但Debug模式下运行效率是Rust的几乎2倍,但Release模式下,Rust(并发)只是比D(并行)稍快3秒!!! 。准备有时间再写D的并发。。。
但此时没有内存消耗,显示不出Rust的RAll特性。
D语言的代码简洁、高效非常吸引人。