查看命令执行的时间

如果将%time放在输入行的开始,那么命令执行的时间会显示在命令的输出之后。例如,我们可以比较几种不同求幂运算的时间。下面的时间在不同的电脑和不同的Sage版本中可能很不一样。首先看原生Python的计算时间:

  1. sage: %time a = int(1938)^int(99484)
  2. CPU times: user 0.66 s, sys: 0.00 s, total: 0.66 s
  3. Wall time: 0.66

这表示总共用了0.66秒,”Wall time”即总时间是0.66秒。如果你的电脑还在运行很多其他的程序,那么wall time可能比CPU时间多很多。

下面我们查看用Sage的整数类型计算指数的时间,它是通过Cython调用GMP库实现的。

  1. sage: %time a = 1938^99484
  2. CPU times: user 0.04 s, sys: 0.00 s, total: 0.04 s
  3. Wall time: 0.04

使用PARI的C语言接口:

  1. sage: %time a = pari(1938)^pari(99484)
  2. CPU times: user 0.05 s, sys: 0.00 s, total: 0.05 s
  3. Wall time: 0.05

GMP稍微好一点(跟预期的一样,因为Sage内置的PARI也调用了GMP的整数运算)。

还可以象下面这样使用cputime命令来查看程序块的运行时间。

  1. sage: t = cputime()
  2. sage: a = int(1938)^int(99484)
  3. sage: b = 1938^99484
  4. sage: c = pari(1938)^pari(99484)
  5. sage: cputime(t) # somewhat random output
  6. 0.64
  1. sage: cputime?
  2. ...
  3. Return the time in CPU second sinceSagestarted, or with optional
  4. argument t, return the time since time t.
  5. INPUT:
  6. t -- (optional) float, time in CPU seconds
  7. OUTPUT:
  8. float -- time in CPU seconds

walltimecputime类似,只是它计算的是wall time.

我们还能计算Sage中包含的其他计算机代数系统的运算能力。 下面的例子中,每个系统我们都先执行一个无关紧要的命令来启动相应程序。最接近的时间是wall time。然而,如果wall time和CPU时间差的较多时,说明有可能存在性能方面的差异。

  1. sage: time 1938^99484;
  2. CPU times: user 0.01 s, sys: 0.00 s, total: 0.01 s
  3. Wall time: 0.01
  4. sage: gp(0)
  5. 0
  6. sage: time g = gp('1938^99484')
  7. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  8. Wall time: 0.04
  9. sage: maxima(0)
  10. 0
  11. sage: time g = maxima('1938^99484')
  12. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  13. Wall time: 0.30
  14. sage: kash(0)
  15. 0
  16. sage: time g = kash('1938^99484')
  17. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  18. Wall time: 0.04
  19. sage: mathematica(0)
  20. 0
  21. sage: time g = mathematica('1938^99484')
  22. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  23. Wall time: 0.03
  24. sage: maple(0)
  25. 0
  26. sage: time g = maple('1938^99484')
  27. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  28. Wall time: 0.11
  29. sage: gap(0)
  30. 0
  31. sage: time g = gap.eval('1938^99484;;')
  32. CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
  33. Wall time: 1.02

这个测试中,GAP和Maxima最慢(使用的是sage.math.washington.edu的主机)。 由于pexpect接口的开销,将这些与Sage进行比较可能是不公平的。