โปรแกรม หาผลรวม และ ค่าเฉลี่ย (เขียนด้วยภาษา Python)

พอดีเมื่อวานผมจำเป็นต้องทำงานประมวลผลข้อมูลตัวเลขที่รับมาจาก standard input แต่ละบรรทัด แล้วนำตัวเลขเหล่านั้นไปหาผลรวมและค่าเฉลี่ย (ตัวเลขพวกนี้เป็นผลลัพธ์จากการรันอีกโปรแกรมหนึ่ง) ผมก็นึกหาคำสั่งใน Linux/Unix ว่ามีคำสั่งพวกหาผลรวมทุกบรรทัดว่ามีหรือเปล่าแต่ก็นึกไม่ออก เลยลองถามพี่เฉิงดูว่ามีคำสั่งดังกล่าวหรือไม่ แต่ผมก็ได้รับข่าวร้ายและข่าวดีจากพี่เฉิงว่า "ไม่มี tool นี้หรอก แต่พี่มี perl script เขียนไว้แล้ว" ผมล่ะปลาบปลื้มปิติจริง ๆ ที่มีรุ่นพี่เก่ง ๆ อย่างพี่เฉิงคอยแนะนำ ผมจึงนำเอา perl script ของพี่เฉิงมาใช้งานซึ่งมันก็สามารถทำงานได้ดีทีเดียว แต่ทว่าผมเขียน Perl ไม่เป็น และ script ของพี่เฉิงก็ยังมีบักนิดหน่อยในกรณีที่ไม่มี input เข้ามามันจะเกิดข้อผิดพลาดแบบ division by zero ขึ้น...

ดังนั้นผมเลยนำมาเขียนใหม่ด้วยภาษา Python เพื่อที่ผมจะได้แก้ไขปรับปรุงได้เองในอนาคต จึงได้โปรแกรมซึ่งมีชื่อว่า sumstat.py ดังนี้:

#!/usr/bin/env python import sys # Initialize each variable. sum = 0.0 sumsq = 0.0 count = 0 mean = 0.0 variant = 0.0 # Read a number from stdin until EOF is found. line = sys.stdin.readline() while (line): try: number = float(line) count += 1 sum += number sumsq += number * number except: # If an input is not a valid number, # read the next input. continue finally: line = sys.stdin.readline() if count > 0: mean = sum / count variant = (sumsq / count) - (mean * mean) print "count: ", count print "sum: ", sum print "mean: %5f" % mean print "variant: %5f" % variant

วิธีนำไปประยุกต์ใช้ ตัวอย่างเช่น:
ถ้าคุณต้องการหาว่า แต่ละ process ในเครื่องของคุณนั้นใช้ CPU หรือ Memory ไปกี่เปอร์เซ็นต์ หรือหาค่าเฉลี่ยของ CPU% หรือ MEM% ของทุก ๆ process คุณก็สามารถทำได้โดยรันคำสั่งต่อไปนี้:

$ ps aux | tr -s \ | cut -f3 -d\ | sumstat.py

ขออธิบายคำสั่งด้านบนนะครับ

  • ps aux #เป็นคำสั่งที่ใช้ดูข้อมูลของทุก ๆ process ที่กำลังทำงานอยู่
  • tr -s \  #เป็นคำสั่งที่ใช้ในการลบช่องว่าง(space)ที่ซ้ำ ๆ กันให้เหลือเพียงช่องว่างเพียงตัวเดียว ที่ต้องเรียกคำสั่งนี้เพื่อให้ง่ายในการตัดข้อมูลด้วยคำสั่งต่อไป
  • cut -f3 -d\  #เป็นคำสั่งที่ใช้ตัดเอาเฉพาะข้อมูลในคอลัมน์ที่ 3 ของผลลัพธ์ที่ได้จากคำสั่ง ps aux ซึ่งก็คือ CPU% โดยใช้ช่องว่างเป็นตัวแบ่งข้อมูลแต่ละคอลัมน์
  • sumstat.py #โปรแกรมของเราเองซึ่งจะให้แสดงผลลัพธ์ เป็นค่าผลรวม ค่าเฉลี่ย และ variant ออกมา

ป.ล. หวังว่าโปรแกรมนี้คงมีประโยชน์สำหรับผู้อื่นไม่มากก็น้อยนะครับ :)

AttachmentSize
sumstat.py.txt617 bytes

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd><img> <object> <embed> <param>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.
ญาณรักข์ วรรณสาย