繁体   English   中英

如何减少 Python 代码将数据写入镶木地板文件所花费的时间?

[英]how to decrease time taken by the Python code to write data to parquet file?

我有在 pyspark 环境中编写的 python 程序。 写了多行 pyspark 转换,但执行起来几乎不需要 45 秒。 但是应该将行(数据)写入镶木地板文件格式的目标位置的最终数据帧大约需要 5 分 35 秒。 下面是行号

No of records in the file: 7143779

下面是写入镶木地板格式的代码片段

final_df = func.union_dataframes([df1.select(<cols>), df2.select(cols)])
cur_time_str = func.get_current_timestamp_for_curate_container()
if time_frame == "20000":
  cur_path = <destination_path> + curate_time_str + "abc"
else:
  cur_path = <destination_path> + cur_time_str + "_" + time_frame + "_xyz"
func.write_df_as_parquet_file(final_df, cur_path, logger)

下面是我们调用来编写 parquet 文件的代码片段

def write_df_as_parquet_file(df, path, logger):
    try:
        df.write.mode('overwrite').parquet(path)
        logger.debug(
            f'File written Successfully at {path} , No of records in the file : { str(df.count())}')
        print(
            f'File written Successfully at {path} , No of records in the file : { str(df.count())}')
    except Exception as exc:
        return_code = 'file Writting Exception: ' + \
            path + '\n' + 'Exception : ' + str(exc)
        print(return_code)
        logger.error(return_code)
        raise

有没有办法减少我可以在上面的 function 或任何其他方式中实施的此流程所花费的时间?

谢谢你。

当您在write_df_as_parquet_file pyspark 中调用df.count()实际上再次计算 df 时,您没有缓存结果。 您可以通过添加以下行来减少运行时间,该行在保存后读取镶木地板:

        df.write.mode('overwrite').parquet(path)
        df = spark.read.parquet(path)
        logger.debug(
            f'File written Successfully at {path} , No of records in the file : { str(df.count())}')
        print(
            f'File written Successfully at {path} , No of records in the file : { str(df.count())}')

您报告 I/O 吞吐量为 21 K 记录/秒,并且正在寻找更高的吞吐量。

验证这是可行的。 您没有提到传输了多少字节(每条记录或总计),因此我们不知道 I/O 子系统正在处理多少字节/秒。 使用dd复制您的文件,并将其吞吐量与您的应用程序的吞吐量进行比较。 验证您的应用是否像dd一样受 I/O 限制。


在分析的这一点上,您可能已经得出结论,要减少经过的时间,您需要写入更少的字节。

好消息。 Parquet 提供了几种无损压缩算法。 缺点是它可能会让你受 CPU 限制,而且阅读变得更加昂贵。 并且您可能阅读的次数比编写的次数多得多,请尝试使用 snappy 或其竞争对手。 并确定哪种压缩方法最适合您的用例。 在这里报告您的发现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM