【问题标题】:Why Import-Csv's Sort-Object is slow for 1 million records为什么 Import-Csv 的 Sort-Object 对于 100 万条记录很慢
【发布时间】:2021-02-02 23:39:22
【问题描述】:

我需要对 csv 文件的第一列(列可能不同)进行排序。 由于我的 csv 文件有超过一百万条记录,因此执行以下命令需要 10 分钟。

有没有其他方法可以优化代码以加快执行速度?

$CsvFile = "D:\Performance\10_lakh_records.csv"
$OutputFile ="D:\Performance\output.csv"

    Import-Csv $CsvFile  | Sort-Object { $_.psobject.Properties.Value[1] } | Export-Csv -Encoding default -Path $OutputFile -NoTypeInformation

【问题讨论】:

  • 你只做Import-Csv $CsvFile | Export-Csv ...需要多长时间? IE。 Sort-Object 真的是这里的瓶颈吗?另外,您是否尝试过here 所述的“从第一行提取”方法?应该会更有效率。
  • 10Laks 多少钱?
  • 如果你只做| Sort-Object 会发生什么?
  • 是瓶颈是排序对象。没有排序对象的执行已在 40 秒内完成。
  • @Theo 1 Lak(h) 是 10^5,所以 10 = 100 万

标签: powershell


【解决方案1】:

您可以尝试使用[array]::Sort() 静态方法,它可能比Sort-Object 更快,尽管它确实需要额外的步骤来首先获取所有值的一维数组以进行排序..

试试

$CsvFile    = "D:\Performance\10_lakh_records.csv"
$OutputFile = "D:\Performance\output.csv"

# import the data
$data = Import-Csv -Path $CsvFile

# determine the column name to sort on. In this demo the first column
# of course, if you know the column name you don't need that and can simply use the name as-is
$column = $data[0].PSObject.Properties.Name[0]

# use the Sort(Array, Array) overload method to sort the data by the 
# values of the column you have chosen.
# see https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-5.0#System_Array_Sort_System_Array_System_Array_
[array]::Sort($data.$column, $data)

$data | Export-Csv -Encoding default -Path $OutputFile -NoTypeInformation

【讨论】:

  • 是的,它比 Sort-Object 快得多。排序对象的一半时间。谢谢。
猜你喜欢
  • 2016-04-12
  • 2021-11-27
  • 2021-11-07
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
  • 2022-10-21
  • 2017-01-31
相关资源
最近更新 更多