有没有办法测量这个算法解决这个 Soduku 拼图所花费的时间?
Posted
技术标签:
【中文标题】有没有办法测量这个算法解决这个 Soduku 拼图所花费的时间?【英文标题】:Is there a way to measure the time taken this algorithm takes to solve this Soduku Puzzle? 【发布时间】:2021-03-15 10:35:55 【问题描述】:我有代码可以使用回溯算法解决数独难题。我想知道回溯算法使用 python 语言在几秒或几毫秒内解决数独难题需要多长时间。
我的代码是 '''
from tabulate import tabulate
import timeit
# A 9x9 matrix which represents our sudoku solver
sudoku_board = [
[0,0,0,0,0,0,2,0,0],
[0,8,0,0,0,7,0,9,0],
[6,0,2,0,0,0,5,0,0],
[0,7,0,0,6,0,0,0,0],
[0,0,0,9,0,1,0,0,0],
[0,0,0,0,2,0,0,4,0],
[0,0,5,0,0,0,6,0,3],
[0,9,0,4,0,0,0,7,0],
[0,0,6,0,0,0,0,0,0]
]
# Display the board
def display_board(sudoku_board):
print(tabulate(sudoku_board, tablefmt='fancy_grid'))
#Look for an unassigned cell if it exists return row and col values else return False
def empty_cells_exist():
for i in range(9):
for j in range(9):
if sudoku_board[i][j] == 0:
return [i, j]
return False
# Is our choice good or not?
def valid_number_check(num, i, j):
#Checking vertically
for row in range(9):
if sudoku_board[row][j] == num:
return False
#Checking horizontally
for col in range(9):
if sudoku_board[i][col] == num:
return False
#Check in the 3x3 gird / box
grid_row = (i // 3) * 3
grid_col = (j // 3) * 3
for i in range(3):
for j in range(3):
if sudoku_board[grid_row + i][grid_col + j] == num:
return False
# Once all tests are passed return true
return True
# Solver
def solver():
cells_exist = empty_cells_exist()
if not cells_exist:
return True
i, j = cells_exist[0], cells_exist[1]
for num in range(1,10):
if valid_number_check(num, i, j):
sudoku_board[i][j] = num
#Backtracking (checking the next step)
if solver():
return True
else:
sudoku_board[i][j] = 0
# False if nothing (1 through 9) yield an "accepted answer"
return False
display_board(sudoku_board)
if solver():
display_board(sudoku_board)
else:
print("no solution available")
if __name__ == "__main__":
print(timeit.timeit(solver,number=10000))
,,,
如您所见,我尝试为求解器函数计时,但它返回的数字类似于 0.07027392299999846,这不是所需的格式。我要求它以清晰易读的格式供人类理解。比如分秒格式。
【问题讨论】:
您可以在文档中阅读它,它以秒为单位。请参阅:docs.python.org/3/library/timeit.html。它与您认为需要多长时间一致吗?注意:“默认情况下,timeit() 在计时期间会暂时关闭垃圾收集。这种做法的优点是它使独立计时更具可比性。缺点是GC可能是被测函数性能的重要组成部分. 如果是这样,GC 可以作为设置字符串中的第一条语句重新启用。”详情见链接。 【参考方案1】:为此,我通常使用datetime.datetime.now
:
>>> import datetime
>>> begin = datetime.datetime.now()
>>> begin
datetime.datetime(2021, 3, 15, ..., 40, 14, 560666)
>>> end = datetime.datetime.now()
>>> end - begin
datetime.timedelta(seconds=10, microseconds=530067)
>>> str(_)
'0:00:10.530067' # the nice representation
或者自己构造timedelta
object:
>>> datetime.timedelta(seconds=0.07027392299999846)
datetime.timedelta(microseconds=70274)
>>> str(_)
'0:00:00.070274'
所以您的代码可能如下所示:
dt = timeit.timeit(solver,number=10000)
print(datetime.timedelta(seconds=dt))
【讨论】:
【参考方案2】:您可以使用模块时间来测量所花费的时间
import time
time1=time.time()
#code
time2=time.time()
time=time2-time1
print(f"time taken timne seconds")
【讨论】:
以上是关于有没有办法测量这个算法解决这个 Soduku 拼图所花费的时间?的主要内容,如果未能解决你的问题,请参考以下文章