2

出于测试目的,我想创建一个小实用程序,它会提示我输入要创建的文件的大小以及要发送到的位置,然后在记录之前记录创建文件所需的时间Excel 电子表格中的结果。到目前为止,我有这个:

import time
import pythoncom
from win32com.client import Dispatch

#create file
myPath = input('Where do you want to write the file?')
size_MB = int(input('What sized file do you want to test with? (MB)'))
size_B = size_MB * 1024 * 1024
fName = '\pydatafile'
#start timer
start = time.clock()
f = open(myPath + fName,'w')
f.write("\x00" * size_B)
f.close()

#how much time it took
elapsed = (time.clock() -start)
print ("It took", elapsed, "seconds to write the", size_B, "MB file")
#I'll sort something out to work out Mbps when the rest is ready

#record results on Excel
xl = Dispatch('Excel.Application')
xl.visible= 0
wb = xl.Workbooks.Add(r'C:\Users\ryansinfield\Desktop\Book1.xlsm')
ws = wb.Worksheets(1)

#loop until empty cell is found in column
col = 1
row = 1
empty = False

while not empty:
    val = ws.Cells(row,col).value
    print("Looking for next available cell to write to...")
    if val == None:
        print("Writing result to cell")
        ws.Cells(row,col).value = Mbps
        empty = True
    row += 1

xl.Run('Save')
xl.Quit()

pythoncom.CoUninitialize()

这会在指定位置创建一个文件,但文件创建是即时的。我为文件指定的大小无关紧要,它始终显示为 0 字节并需要微秒来创建。

有什么方法可以创建一个实际的文件,让我更有效地测试 LAN 速度?

编辑:它现在似乎在速度方面起作用。我不知道为什么会这样,也许我是个笨蛋。不过有一点我想补充。测试运行后是否可以删除空白文件?

4

1 回答 1

0

您可能会发现一些有趣的事情:

  • 内置os模块有一些很好的功能来做文件系统的东西:

    • 使用该os.path模块,您在处理路径时不必担心依赖于平台的语法或反斜杠。

    • 您可以使用os.remove删除文件。

  • 因为您使用的是 Excel,所以我猜您使用的是 Windows:在写入文件时考虑使用“wb”而不是“w”,因为Windows 处理 EOL 字符的方式与 Unix 不同。

  • "0.Df"%number可用于格式化带有 D 个小数位的浮点数。

添加了这些更改的代码:

import os
import time
import pythoncom
from win32com.client import Dispatch

#create file
myDir = input('Where do you want to write the file?')
myPath = os.path.join(myDir, 'pydatafile')

size_MB = int(input('What sized file do you want to test with? (MB): '))
size_B = size_MB * 1024 * 1024

# create string to write
to_write = "\x00" * size_B

#start timer
start = time.clock()
f = open(myPath, 'wb')
f.write(to_write)
f.close()

#how much time it took
elapsed = time.clock() - start
print "It took %0.3f"%elapsed, "seconds to write the", size_MB, "MB file at a rate of %0.3f"%(size_MB/elapsed), "Mbps."

#record results on Excel
xl = Dispatch('Excel.Application')
xl.visible= 0
wb = xl.Workbooks.Add(r'C:\Users\ryansinfield\Desktop\Book1.xlsm')
ws = wb.Worksheets(1)

#loop until empty cell is found in column
col = 1
row = 1
empty = False

while not empty:
    val = ws.Cells(row,col).value
    print("Looking for next available cell to write to...")
    if val == None:
        print("Writing result to cell")
        ws.Cells(row,col).value = Mbps
        empty = True
    row += 1

xl.Run('Save')
xl.Quit()

pythoncom.CoUninitialize()

# Remove the file at the end
os.remove(myPath)
于 2013-10-11T20:56:52.307 回答