24小时热门版块排行榜    

CyRhmU.jpeg
南方科技大学公共卫生及应急管理学院2025级博士研究生招生报考通知
查看: 3777  |  回复: 27
当前只显示满足指定条件的回帖,点击这里查看本话题的所有回帖

zdzqy

新虫 (小有名气)

[求助] Mathematica里的compile怎么使用已有1人参与

请教一下各位:Mathematica里的compile怎么使用?我现在的程序里需要一个大的循环数组,计算的时间太长,想提高一下计算速度。
回复此楼
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

walk1997

金虫 (著名写手)

引用回帖:
7楼: Originally posted by chyanog at 2013-08-03 20:11:32
Compile一点也不鸡肋,并不是只能编译一些简单函数,一些数值计算程序可以提速30~100倍以上,但使用一些高级的函数时(NSolve,NIntegrate等)就没必要Compile了,不会有加速效果,
使用CompilationTarget -> & ...

闲着 又琢磨了下这个代码
我感觉完成这个功能mathematica本身的代码会这样
test2[m_] :=
  Position[FractionalPart@Sqrt@Array[(1.0 #1^2 + 1.0 #2^2) &, {m, m}],
  0.0];
(test2[1000] // Length)/2 // AbsoluteTiming
这样的代码速度大概比编译的慢5倍 (扣去本身重复计算了一半 大概是2-3倍 编译的效果还是明显 这里position大约花了一半的时间)
不知道mathematica本身的代码能否再优化下?
11楼2013-08-07 11:29:11
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
查看全部 28 个回答

mshwangg

至尊木虫 (正式写手)

【答案】应助回帖


感谢参与,应助指数 +1
zdzqy: 金币+1, ★★★很有帮助 2013-08-07 10:40:49
Mathematica帮助文件里关于Compile有这样两段话:
If you make a definition like f[x_]:=x Sin[x], Mathematica will store the expression x Sin[x] in a form that can be evaluated for any x. Then when you give a particular value for x, Mathematica substitutes this value into x Sin[x], and evaluates the result. The internal code that Mathematica uses to perform this evaluation is set up to work equally well whether the value you give for x is a number, a list, an algebraic object, or any other kind of expression.
Having to take account of all these possibilities inevitably makes the evaluation process slower. However, if Mathematica could assume that x will be a machine number, then it could avoid many steps, and potentially evaluate an expression like x Sin[x] much more quickly.

看明白了吧?Mathematica处理一个变量的时候要考虑很多种可能的情况,比如说这个变量是实数、复数、数组还是代数符号等等,所以处理起来比较慢。而用Compile不过是设定使用的变量是具体的那种数据类型,计算起来当然要快一些。

实际上,个人认为Compile的功能有点鸡肋,它不生成可执行文件,也不可以脱离Mathematica环境运行程序。如果在程序中每个变量在使用之前赋值并且所有可能的函数都做数值运算,比如NSolve,NIntegrate,那么Compile与否其实差别不大,不会为你节省多少时间。

Complie的使用方法参考:在Mathematica里键入“Compile”,全选,按键盘上的“F1”!
虽然等于没说,但是比说了还详细。
2楼2013-06-04 09:39:06
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

walk1997

金虫 (著名写手)

1. 安装好C
2. 直接调用complile。
对于复杂函数的计算的 还是有比较明显速度的提高的
不过编译成C和VM的 看起来差别不是很大 也许非常复杂的表达式会有差别
另外 如果是表达式非常复杂的话 最好相优化下表达式
an example to show the difference
Clear["Globale`*"];
f[x_Real] := x^2 + 1;
c1 = Compile[ {{x, _Real}}, x^2 + 1, CompilationTarget -> "C"];
c2 = Compile[ {{x, _Real}}, x^2 + 1];
Do[c1, {i, 1.0, 10.0^6, 1.0}] // Timing
Do[c2, {i, 1.0, 10.0^6, 1.0}] // Timing
Do[f, {i, 1.0, 10.0^6, 1.0}] // Timing
Do[c1, {i, 1, 10^6, 1}] // Timing
Do[c2, {i, 1, 10^6, 1}] // Timing
Do[f, {i, 1, 10^6, 1}] // Timing
3楼2013-06-06 08:23:10
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

walk1997

金虫 (著名写手)

最下面几行 碰到 时候 总是出错 看来以后改成 [j]
4楼2013-06-06 08:24:22
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
信息提示
请填处理意见