Part2:比较两个渗透函数的性能

关于该部分的项目描述请见Project2 Percolation in Grids 网格渗透

  测试的场景要求如下:

·         set n=75

·         consider values of p from 0 to 1 in increments of 0.05 (or smaller)

·         for each value of p, generate 10 random grids and record for each algorithm the average running time on the ten grids

   可是我在编写该部分的测试代码时,遇到了些麻烦,一开始还摸不清头脑。

 

My Problem that You should Avoid

 

  我的思路是执行每次for循环前,也就是对于每个p值,产生一个当前时间t,然后每发生渗透,记录下时间差time_delta,并设置一个求和变量sum_time,累加每次的执行时间。代码如下,发现我错在哪了么?

def test_time(func):    #这是错误的
    p = 0
    results 
= []
    
while p < 1:
        
print 'Running for p =', p, '...'
        sum_time
=0
        t 
= time.clock()
        
for k in range(trial_count):
            g 
= random_grid(size, p)
            flow,perc 
= func(g, trace=False)
            
if perc:
                time_delta
= time.clock()-t
                sum_time
+=time_delta

        Aver_time 
= float(sum_time)/trial_count
        
print Aver_time        
        results.append(Aver_time)
        p 
+= step
        
    
return results

第一,错在不用为每一次运算计算运行时间,只要每执行trial_count次,跳出循环,计算一次时间差即可。

第二,算法的执行时间不是仅指发生渗透的情况下啊! 我错了,我真的错了...

   正确的代码应该如下:

    p = 0
    results 
= []
    old_clock 
= time.clock()
    
print 'testing', func, '...'

    
while p < 1:
        
print 'Running for p =', p, '...'
        perc_count 
= 0
        
for k in range(trial_count):
            g 
= random_grid(size, p)
            flow,perc 
= func(g,trace=False)
        new_clock 
= time.clock()
        results.append((new_clock 
- old_clock)/trial_count)
        old_clock 
= new_clock
        p 
+= step


    附上美丽的曲线图,经过一段曲折的纠缠,最终水波算法胜出

 

 

测试的完整代码,贴在这里,至此Python的网格渗透项目也完全结束

# -*- coding: utf-8 -*-
"""
Created on Wed Aug 10 13:34:21 2011

@author: Nupta
"""

from percolation_wave import *
from my_percolation_recursive import *
from pylab import *
import time
import sys

step 
= 0.05
trial_count 
= 10
size 
= 75


def test_time(func):
    p 
= 0
    results 
= []
    old_clock 
= time.clock()

    
print 'testing', func, '...'

    
while p < 1:
        
print 'Running for p =', p, '...'

        perc_count 
= 0
        
for k in range(trial_count):
            g 
= random_grid(size, p)
            flow,perc 
= func(g,trace=False)
        new_clock 
= time.clock()
        results.append((new_clock 
- old_clock)/trial_count)
        old_clock 
= new_clock
        p 
+= step

    
return results

if __name__ == '__main__':
    
    sys.setrecursionlimit(
250000)
    
    res1 
= test_time(percolation_wave)
    res2 
= test_time(percolation_recursive)

    plot(arange(0,
1,step), res1, 'b', label='wave')
    plot(arange(0,
1,step), res2, 'r', label='recursive')
    legend()
    xlabel(
'p')
    ylabel(
'Running Time')
    title(
'Running Time')
    show()

 

 

 

 

posted @ 2011-08-10 14:22  牛皮糖NewPtone  阅读(401)  评论(0编辑  收藏  举报