excel 如何固定时间测量栏

ghhaqwfi  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(139)

我想用python和pycharm来测量一个程序的执行时间。下面是我使用的代码。

import time
import pandas as pd

# get the start time
st_wall = time.time()
st = time.process_time()

df_time = pd.DataFrame(columns=['Total Execution time (s)','CPU Execution time (s)'])

# get the end time
et_wall = time.time()
et_process = time.process_time()

# get execution time
wall_clock_time = et_wall - st_wall
res = et_process - st

# get execution time
wall_clock_time = et_wall - st_wall
res = et_process - st

print('Total Execution time:', wall_clock_time, 'seconds')
print('CPU Execution time:', res, 'seconds')

time_row={'Total Execution time (s):': wall_clock_time, 'CPU Execution time (s)':res}
df_time = df_time.append(time_row, ignore_index=True)

#import data to excel
datatoexcel = pd.ExcelWriter('lambda summary by setting random range sample size 100.xlsx')

# write DataFrame to excel
df_time.to_excel(datatoexcel, sheet_name='Calculation Time')

# save the excel
datatoexcel.save()
print('DataFrame is written to Excel File successfully.')

预期结果为:

但是,代码的当前结果如下所示。

有谁能告诉我需要修改的地方吗?先谢谢你。

njthzxwz

njthzxwz1#

您的问题不清楚。您是否尝试将函数的多次运行记录到一个表中?我不确定您为什么创建一个空 Dataframe ,然后将一次运行附加到它(注意,我收到一个错误,说Pandas中的append函数即将过期)。
我对excel不太确定,因为我没有excel,但是我制作了一个代码,可以填充一个数据框进行多次运行。使用你的代码,我假设数据框会正确地保存到excel中。

import time
import pandas as pd
import numpy as np
import math

def func(x):
    L=[]
    for i in range(1000000):
        a=math.sqrt(x^5)
        L.append(a)
    return np.sum(L)

total_list=[]
cpu_list=[]

for i in range(10):
    # get the start time
    st_wall = time.time()
    st = time.process_time()

    func(1000)

    # get the end time
    et_wall = time.time()
    et_process = time.process_time()

    # get execution time
    wall_clock_time = et_wall - st_wall
    res = et_process - st

    total_list.append(wall_clock_time)
    cpu_list.append(res)

df_time=pd.DataFrame({'Total Execution time (s):': total_list, 'CPU Execution time (s)': cpu_list})
print(df_time)

#import data to excel
datatoexcel = pd.ExcelWriter('lambda summary by setting random range sample size 100.xlsx')

# write DataFrame to excel
df_time.to_excel(datatoexcel, sheet_name='Calculation Time')

# save the excel
datatoexcel.save()
print('DataFrame is written to Excel File successfully.')

相关问题