我试图理解为什么以下AppleScript处理程序在如此不同的时间内完成。我已经开始(!)阅读一些关于Big O和复杂性的内容,但我正在努力将我迄今为止有限的理解应用于这些案例:
处理程序1:
on ranger1(n)
set outList to {}
repeat with i from 1 to n
set end of outList to i
end repeat
return outList
end ranger1
处理程序2:
on ranger2(n)
set outList to {}
set i to 1
repeat n times
set end of outList to i
set i to i+1
end repeat
return outList
end ranger2
我已经尝试过这些处理程序,其中n的值高达1 000 000.(如果有人在阅读计划中尝试这些,请坚持使用值<= 100,000 ! )
定时拨打ranger1(100000)
:
set timeStart to (time of (current date))
ranger1(100000)
log (time of (current date)) - timeStart
给我一段8-10秒的时间来完成。
然而,定时拨打ranger2(100000)
会导致约240秒完成。
我假设在ranger2()
中,语句set i to i+1
正在增加处理程序的“复杂性”。我可能错了,我可能是对的;我老实说不知道。
所以,我猜我的问题是(!) - 我错了吗?
我将非常感谢任何可以帮助我理解这些处理程序之间真正区别的解释。特别是可以帮助我将“复杂性”的概念应用于这种简单功能。
干杯:)
答案 0 :(得分:0)
Big O告诉您随着数据大小的增加,运行时间将如何发展。 所以它实际上并没有什么实际意义,只有一条经验法则。
你的发现表明,从1到n循环使用i重复有点快,因为计数器会在幕后增加。如果你试着在理论上测量东西,那么i + 1当然也算作一个额外的陈述。 :)
答案 1 :(得分:0)
为了比较,这里是Python中的等价物(我花了一周的时间才开始使用AppleScript,而且我是一个慢学习者):
#!/usr/bin/python
from time import time
def ranger3(n):
outlist = []
i = 1
for _ in range(n):
outlist.append(i)
i += 1
return outlist
def ranger4(n):
outlist = []
for i in range(1, n+1):
outlist.append(i)
return outlist
n = 10000000 # 10 million
t = time()
ranger3(n)
print(time()-t) # 2.2633600235
t = time()
ranger4(n)
print(time()-t) # 1.52647018433
毋庸置疑,除了比AS快一两级之外,两者都是O(n)
- 与大多数主流语言相比,Python被认为是慢的。只是为了表明对于性能优化&#34;是多么无意义。 AppleScript,当所有其他语言都直接开箱即用时。
答案 2 :(得分:0)
我在上面提供的AS游侠代码上运行了以下定时器循环:
set minIter to 0
set maxIter to 200000
set incIter to 50000
repeat with iters from minIter to maxIter by incIter
set timeStart to (time of (current date))
ranger1(iters)
log (" ranger1(" & iters & ") took seconds:" & (time of (current date)) - timeStart) & " seconds "
end repeat
repeat with iters from minIter to maxIter by incIter
set timeStart to (time of (current date))
ranger2(iters)
log (" ranger2(" & iters & ") took seconds:" & (time of (current date)) - timeStart) & " seconds "
end repeat
这些结果:
(* ranger1(0) took seconds:0 seconds *)
(* ranger1(50000) took seconds:1 seconds *)
(* ranger1(100000) took seconds:3 seconds *)
(* ranger1(150000) took seconds:8 seconds *)
(* ranger1(200000) took seconds:13 seconds *)
(* ranger2(0) took seconds:0 seconds *)
(* ranger2(50000) took seconds:74 seconds *)
(* ranger2(100000) took seconds:262 seconds *)
(* ranger2(150000) took seconds:471 seconds *)
(* ranger2(200000) took seconds:734 seconds *)
当然,ranger1(相对)更快,但绝对不是线性的,而且ranger2是彻头彻尾的冰川。