1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[awk]小数の切り上げ(速度比較)

Posted at
  • 小数の切り上げ処理という頻度の高い処理をawkで行うためのメモ
  • 大体記法や速度の面において、忘れるため備忘録として記録。

結果

  • 以下の内容から、方法2の方が速い。
  • ただ可読性や速度の誤差の点から、方法1を利用する。
  • ※forを利用した方法は、awkでは順番が変わるため記録としては除外。

内容

# テストデータ作成
seq 1 0.2 100000 > number

# 最初の10行表示
cat number | head -n 5

1
1.2
1.4
1.6
1.8

# 方法1 int関数を用いる
cat number | awk '{r=int($1); print (r==$1) ? r : r+1}' | head -n 5

1
2
2
2
2

# 方法1の速度検証
# 0.00s user 0.00s system 1% cpu 0.492 total
time cat number | awk '{r=int($1); print (r==$1) ? r : r+1}' > /dev/null

# 方法2 printfを利用する
cat number | awk '{printf("%d\n",$1+=$1<0?0:0.999)}' | head -n 5

1
2
2
2
2

# 方法2の速度検証
# 0.00s user 0.00s system 0% cpu 0.476 total
time cat number | awk '{printf("%d\n",$1+=$1<0?0:0.999)}' > /dev/null

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?