Showing posts with label monitor. Show all posts
Showing posts with label monitor. Show all posts

Saturday, August 6, 2011

network engineer tool


SNMP Enabler for Windows

(17)
 | 
Save time by remotely installing, enabling, and configuring SNMP on multiple Windows servers and workstations.
Download Now »

Saturday, April 16, 2011

Reference

RedHat has sysstat preinstalled and collect system activity data routinely. It logs it in the /var/log/sa directory.  For Suse it needs to be installed manually.
Linux implementation is well described in Linux.com article  CLI Magic Tracking system performance with sar
Sadc (system activity data collector) is the program that gathers performance data. It pulls its data out of the virtual /proc filesystem, then it saves the data in a file (one per day) named /var/log/sa/saDD where DD is the day of the month. Two shell scripts from the sysstat package control how the data collector is run. The first script, sa1, controls how often data is collected, while sa2 creates summary reports (one per day) in /var/log/sa/sarDD. Both scripts are run from cron. In the default configuration, data is collected every 10 minutes and summarized just before midnight.
If you suspect a performance problem with a particular program, you can use sadc to collect data on a particular process (with the -x argument), or its children (-X), but you will need to set up a custom script using those flags.
As Dr. Heisenberg showed, the act of measuring something changes it. Any tool that collects performance data has some overall negative impact on system performance, but with sar, the impact seems to be minimal. I ran a test with the sa1 cron job set to gather data every minute (on a server that was not busy) and it didn't cause any serious issues. That may not hold true on a busy system.
Creating reports
If the daily summary reports created by the sa2 script are not enough, you can create your own custom reports using sar. The sar program reads data from the current daily data file unless you specify otherwise. To have sar read a particular data file, use the -f /var/log/sa/saDD option. You can select multiple files by using multiple -f options. Since many of sar's reports are lengthy, you may want to pipe the output to a file.
To create a basic report showing CPU usage and I/O wait time percentage, use sar with no flags. It produces a report similar to this:
01:10:00 PM       CPU     %user     %nice   %system   %iowait     %idle
01:20:00 PM       all      7.78      0.00      3.34     20.94     67.94
01:30:00 PM       all      0.75      0.00      0.46      1.71     97.08
01:40:00 PM       all      0.65      0.00      0.48      1.63     97.23
01:50:00 PM       all      0.96      0.00      0.74      2.10     96.19
02:00:00 PM       all      0.58      0.00      0.54      1.87     97.01
02:10:00 PM       all      0.80      0.00      0.60      1.27     97.33
02:20:01 PM       all      0.52      0.00      0.37      1.17     97.94
02:30:00 PM       all      0.49      0.00      0.27      1.18     98.06
Average:          all      1.85      0.00      0.44      2.56     95.14
If the %idle is near zero, your CPU is overloaded. If the %iowait is large, your disks are overloaded.
To check the kernel's paging performance, use sar -B, which will produce a report similar to this:
11:00:00 AM  pgpgin/s pgpgout/s   fault/s  majflt/s
11:10:00 AM      8.90     34.08      0.00      0.00
11:20:00 AM      2.65     26.63      0.00      0.00
11:30:00 AM      1.91     34.92      0.00      0.00
11:40:01 AM      0.26     36.78      0.00      0.00
11:50:00 AM      0.53     32.94      0.00      0.00
12:00:00 PM      0.17     30.70      0.00      0.00
12:10:00 PM      1.22     27.89      0.00      0.00
12:20:00 PM      4.11    133.48      0.00      0.00
12:30:00 PM      0.41     31.31      0.00      0.00
Average:       130.91     27.04      0.00      0.00
Raw paging numbers may not be of concern, but a high number of major faults (majflt/s) indicate that the system needs more memory. Note that majflt/s is only valid with kernel versions 2.5 and later.
For network statistics, use sar -n DEV. The -n DEV option tells sar to generate a report that shows the number of packets and bytes sent and received for each interface. Here is an abbreviated version of the report:
11:00:00 AM     IFACE   rxpck/s   txpck/s   rxbyt/s   txbyt/s
11:10:00 AM        lo      0.62      0.62     35.03     35.03
11:10:00 AM      eth0     29.16     36.71   4159.66  34309.79
11:10:00 AM      eth1      0.00      0.00      0.00      0.00
11:20:00 AM        lo      0.29      0.29     15.85     15.85
11:20:00 AM      eth0     25.52     32.08   3535.10  29638.15
11:20:00 AM      eth1      0.00      0.00      0.00      0.00
To see network errors, try sar -n EDEV, which shows network failures.
Reports on current activity
Sar can also be used to view what is happening with a specific subsystem, such as networking or I/O, almost in real time. By passing a time interval (in seconds) and a count for the number of reports to produce, you can take an immediate snapshot of a system to find a potential bottleneck.
For example, to see the basic report every second for the next 10 seconds, use sar 1 10. You can run any of the reports this way to see near real-time results.
Benchmarking
Even if you have plenty of horsepower to run your applications, you can use sar to track changes in the workload over time. To do this, save the summary reports (sar only saves seven) to a different directory over a period of a few weeks or a month. This set of reports can serve as a baseline for the normal system workload. Then compare new reports against the baseline to see how the workload is changing over time. You can automate your comparison reports with AWK or your favorite programming language.
In large systems management, benchmarking is important to predict when and how hardware should be upgraded. It also provides ammunition to justify your hardware upgrade requests.

Linux implementation of sar

The SAR suite of utilities originated in Solaris. It became popular and now runs on most flavors of UNIX, including AIX, HP-UX, and Linux.  Sysstat package is installed by default in standard Red Hat installation. For Suse it is not installed by default and you need to install sysstat package manually (package is provided by Novell).

The reason for sar creation was that gathering system activity data from vmstat and iostat is pretty time-consuming. If you try to automate the gathering of system activity data, and creation of periodic repots you naturally come to creation of a tool like sar. To avoid reinventing the bicycle again and again, Sun engineers wrote sar sar (System Activity Reporter) and included it in standard Solaris distribution. The rest is history.

Linux reimplementation is a part of sysstat package and  like in Solaris sar pulls its data out of the virtual /proc filesystem (pioneered by Solaris).

    The sysstat package contains the sar, sadf, iostat, mpstat, and pidstat commands for Linux. The sar command collects and reports system activity information. The statistics reported by sar concern I/O transfer rates, paging activity, process-related activites, interrupts, network activity, memory and swap space utilization, CPU utilization, kernel activities, and TTY statistics, among others. The sadf command may be used to display data collected by sar in various formats. The iostat command reports CPU statistics and I/O statistics for tty devices and disks. The pidstat command reports statistics for Linux processes. The mpstat command reports global and per-processor statistics.

In addition to sar, Linux package provides several other useful utilities:

    sadf(1) -- similar to sar but can write its data in  different formats (CSV, XML, etc.). This is useful to load performance data into a database, or import them in a spreadsheet to make graphs.
    iostat(1) reports CPU statistics and input/output statistics for devices, partitions and network filesystems.
    mpstat(1) reports individual or combined processor related statistics.
    pidstat(1) reports statistics for Linux tasks (processes) : I/O, CPU, memory, etc.
    nfsiostat(1) reports input/output statistics for network filesystems (NFS).
    cifsiostat(1) reports CIFS statistics.

As in Solaris there are two main binaries and two shell scripts that constitute sar package:

    Binaries
        /usr/lib64/sa/sadc  -- System activity data collector binary, a backend to the sar command. Writes binary log of kernel data to the /var/log/sa/sadd file, where the dd parameter indicates the current day
        /usr/bin/sar -- reporting utility
    Scripts
        /usr/lib64/sa/sa1
        /usr/lib64/sa/sa2

System activity data collector binary can monitor a a large number of different metrics, selectable by options:

    Input / Output and transfer rate statistics (global, per device, per partition, per network filesystem and per Linux task / PID).
    CPU statistics (global, per CPU and per Linux task / PID), including support for virtualization architectures.
    Memory and swap space utilization statistics.
    Virtual memory, paging and fault statistics.
    Per-task (per-PID) memory and page fault statistics.
    Global CPU and page fault statistics for tasks and all their children.
    Process creation activity.
    Interrupt statistics (global, per CPU and per interrupt, including potential APIC interrupt sources, hardware and software interrupts).
    Extensive network statistics: network interface activity (number of packets and kB received and transmitted per second, etc.) including failures from network devices; network traffic statistics for IP, TCP, ICMP and UDP protocols based on SNMPv2 standards; support for IPv6-related protocols.
    NFS server and client activity.
    Socket statistics.
    Run queue and system load statistics.
    Kernel internal tables utilization statistics.
    System and per Linux task switching activity.
    Swapping statistics.
    TTY device activity.
    Power management statistics (CPU clock frequency, fans speed, devices temperature, voltage inputs).

Script sa1 calls sadc to write stats to the file

#!/bin/sh
# /usr/lib64/sa/sa1.sh
# (C) 1999-2006 Sebastien Godard (sysstat  wanadoo.fr)
#
umask 0022
ENDIR=/usr/lib64/sa
cd ${ENDIR}
if [ $# = 0 ]
then
# Note: Stats are written at the end of previous file *and* at the
# beginning of the new one (when there is a file rotation) only if
# outfile has been specified as '-' on the command line...
        exec ${ENDIR}/sadc -F -L 1 1 -
else
        exec ${ENDIR}/sadc -F -L $* -
fi

Script sa2 produces reports from the binary file

#!/bin/sh
# /usr/lib64/sa/sa2.sh
# (C) 1999-2006 Sebastien Godard (sysstat  wanadoo.fr)
#
# Changes:
# - 2004-01-22 Nils Philippsen
#   make history configurable
#
HISTORY=7
[ -r /etc/sysconfig/sysstat ] && . /etc/sysconfig/sysstat
[ ${HISTORY} -gt 25 ] && HISTORY=25
S_TIME_FORMAT=ISO ; export S_TIME_FORMAT
umask 0022
DATE=`date  +%d`
RPT=/var/log/sa/sar${DATE}
ENDIR=/usr/bin
DFILE=/var/log/sa/sa${DATE}
[ -f "$DFILE" ] || exit 0
cd ${ENDIR}
${ENDIR}/sar $* -f ${DFILE} > ${RPT}
find /var/log/sa \( -name 'sar??' -o -name 'sa??' \) -mtime +"${HISTORY}" -exec rm -f {} \;

Here are files installed:

/etc/init.d/sysstat
/etc/sysstat
/etc/sysstat/sysstat
/etc/sysstat/sysstat.cron
/etc/sysstat/sysstat.ioconf
/usr/bin/iostat
/usr/bin/mpstat
/usr/bin/pidstat
/usr/bin/sadf
/usr/bin/sar
/usr/lib64/sa
/usr/lib64/sa/sa1
/usr/lib64/sa/sa2
/usr/lib64/sa/sadc  -- System activity data collector.
/usr/sbin/rcsysstat
/usr/share/doc/packages/sysstat
/usr/share/doc/packages/sysstat/CHANGES
/usr/share/doc/packages/sysstat/COPYING
/usr/share/doc/packages/sysstat/CREDITS
/usr/share/doc/packages/sysstat/FAQ
/usr/share/doc/packages/sysstat/README
/usr/share/doc/packages/sysstat/TODO
/usr/share/doc/packages/sysstat/sysstat-8.0.4.lsm
/usr/share/locale/af/LC_MESSAGES/sysstat.mo
/usr/share/locale/da/LC_MESSAGES/sysstat.mo
/usr/share/locale/de/LC_MESSAGES/sysstat.mo
/usr/share/locale/es/LC_MESSAGES/sysstat.mo
/usr/share/locale/fr/LC_MESSAGES/sysstat.mo
/usr/share/locale/it/LC_MESSAGES/sysstat.mo
/usr/share/locale/ja/LC_MESSAGES/sysstat.mo
/usr/share/locale/ky
/usr/share/locale/ky/LC_MESSAGES
/usr/share/locale/ky/LC_MESSAGES/sysstat.mo
/usr/share/locale/nb/LC_MESSAGES/sysstat.mo
/usr/share/locale/nl/LC_MESSAGES/sysstat.mo
/usr/share/locale/nn/LC_MESSAGES/sysstat.mo
/usr/share/locale/pl/LC_MESSAGES/sysstat.mo
/usr/share/locale/pt/LC_MESSAGES/sysstat.mo
/usr/share/locale/pt_BR/LC_MESSAGES/sysstat.mo
/usr/share/locale/ro/LC_MESSAGES/sysstat.mo
/usr/share/locale/ru/LC_MESSAGES/sysstat.mo
/usr/share/locale/sk/LC_MESSAGES/sysstat.mo
/usr/share/locale/sv/LC_MESSAGES/sysstat.mo
/usr/share/locale/vi/LC_MESSAGES/sysstat.mo
/usr/share/man/man1/iostat.1.gz
/usr/share/man/man1/mpstat.1.gz
/usr/share/man/man1/pidstat.1.gz
/usr/share/man/man1/sadf.1.gz
/usr/share/man/man1/sar.1.gz
/usr/share/man/man8/sa1.8.gz
/usr/share/man/man8/sa2.8.gz
/usr/share/man/man8/sadc.8.gz
/var/log/sa


To activate sar you need to either to create a link in /etc/cron.d to /etc/sysstat/sysstat.cron (approach taken by Suse) or copy the file (simpler approach used by Red Hat).

On Suse /etc/init.d/sysstat  creates and deleted symbolic link to cron.d on start and stop commands :

    lrwxrwxrwx 1 root root 25 Sep 12 10:32 sysstat -> /etc/sysstat/sysstat.cron

here is the fragment of the script that does that

case "$1" in
    start)
        echo "Running sadc"
        /usr/lib64/sa/sa1 1>/dev/null 2>&1 \
                && ln -fs /etc/sysstat/sysstat.cron /etc/cron.d/sysstat \
                || rc_failed 1
        rc_status -v
        ;;

    stop)
        echo "Removing sysstat's crontab"
        rm -f /etc/cron.d/sysstat
        rc_status -v
        ;;

This is a neat trick which permits running sadc only on certain runlevels as well as the ability to enable/disable data collection anytime.

On Red Hat  /etc/init.d/sysstat  the script inserts message LINUX RESTART  and  tell sar that the kernel counters have been reinitialized (/usr/lib64/sa/sadc -F -L -).

case "$1" in
  start)
        echo -n "Calling the system activity data collector (sadc): "
        /usr/lib64/sa/sadc -F -L - && touch /tmp/sysstat.run

# Try to guess if sadc was successfully launched. The difficulty
# here is that the exit code is lost when the above command is
# run via "su foo -c ..."
        if [ ! -f /tmp/sysstat.run ]; then
                RETVAL=1
        else
                rm -f /tmp/sysstat.run
        fi
        echo
        ;;
  stop|status|restart|reload)
        ;;
  *)
        echo "Usage: sysstat {start|stop|status|restart|reload}"
        exit 1
esac
exit ${RETVAL}

The sysstat bootscript only needs to run at system startup, therefore only one symlink is required. Create this symlink in /etc/rc.d/rcsysinit.d using the following command

If sar package is activated the crontab for root should contain something like this (this is actual Red Hat file  /etc/cron.d/sysstat ):

# run system activity accounting tool every 10 minutes
*/10 * * * * root /usr/lib64/sa/sa1 1 1
# generate a daily summary of process accounting at 23:53
53 23 * * * root /usr/lib64/sa/sa2 -A;

or for 64-bit Suse the content of the file /etc/sysstat/sysstat.cron looks like

root@usrklxbck01:/etc/init.d # cat /etc/sysstat/sysstat.cron
#crontab for sysstat

# activity reports every 10 minutes everyday
-*/10 * * * *     root  /usr/lib64/sa/sa1 -d 1 1

# update reports every 6 hours
0 */6 * * *       root  /usr/lib64/sa/sa2 -A

# Generate a daily summary of process accounting at 23:53
53 23 * * *       root  /usr/lib64/sa/sa2 -A


As you can see there are two shell scripts sa1 and sa2. The first script invokes the utility sard for collecting the data, the second produces reports.

System Activity Recorder can monitor several system functions related to overall system performance, for example:

    cpu utilization (it is pretty effective tool for spotting CPU bottlenecks)
    hard disk utilization
    terminal IO
    number of files open
    processes running

SAR as many options and provides queuing, paging, CPU and many other metrics. The system maintains a series of system activity counters that record various activities and provide the data that sar reports. The command merely extracts the data in the counters and saves them based on the sampling rate and the number of samples specified to sar. It costs of two programs sarc and sar:

    The sadc command is a data collecting part of the package. It writes in binary format to the specified output file. To run sar in real time type:

        sar -u 2 5

    In this case the sar command calls sadc to access system data.
    
    To report on previously captured data – type
        sar -u -f filename > file
    Two shell scripts /usr/lib/sa/sa1 and usr/ib/sa/sa2 can be run by the cron daemon and provide daily statistics and reports.

Side effects

Any tool that collects performance data has some impact on system performance, but with sar, it seems to be minimal. Even one minute sampling usually does not cause any serious issues. That may not hold true on a system that is very busy.
Alternatives

There is also older and not currently maintained atsar project:

    The atsar command can be used to detect performance bottlenecks on Linux systems. It is similar to the sar command on other UNIX platforms. Atsar has the ability to show what is happening on the system at a given moment. It also keeps track of the past system load by maintaining history files from which information can be extracted. Statistics about the utilization of CPUs, disks and disk partitions, memory and swap, tty's, TCP/IP (v4/v6), NFS, and FTP/HTTP traffic are gathered. Most of the functionality of atsar has been incorporated in the atop project.

http://www.softpanorama.org/Admin/Monitoring/Sar/linux_implementation_of_sar.shtml

Thursday, April 14, 2011

Vmstax – Build charts/graphs from vmstat log

learning Flex 3, i wanted to test the chart functionnalities. As a case study, i took the problematic of drawing charts from a vmstat log. At the end of your load tests, you have to build the charts. It may take  some times to do that with Word or OpenOffice and it is not one of my favorite task. So, i decided to make a littleapplication in Flex : you upload your vmstat log, the chars appears and you can export them as images.

http://www.michenux.net/vmstax-build-vmstat-charts-1.html

Tuesday, April 12, 2011

Monitoring Linux server performance with procallator

I manage a fair number of Linux hosts, and like to keep tabs on how my systems are performing. One way I accomplish this is with procallator, which is a Perl script that collects performance data that can be graphed by orca. The graphs that orca produces are great awesome for trening server performance over time, and can be extremely valuable when debugging performance problems.
To setup procallator to collect performance data, you first need to retrieve the latest orca CVS snapshot from the orcaware snapshots directory (the procallator script is included with the orca snapshot, and the latest version contains a number of fixes). Once orca is downloaded, you will need to extract the tarball and run configure to modify the variables in the header of the procallator script:
$ tar xfj orca-snapshot-r529.tar.bz2
$ cd orca-snapshot-r529
$ ./configure –prefix=/opt/orca-r529 –with-html-dir=/opt/html
After the configure operation completes, you can install the procallator scripts with the Makefile’s install option:
$ make install
This will place the procallator perl script in $PREFIX/bin. To make sure the script starts at system boot, you can copy the $PREFIX/data_gathers/procallator/S99procallator script to /etc/rc3.d (or /etc/init.d depending on how you install your init scripts):
$ cp S99procallator /etc/rc3.d
Once these files are in place, you can start procallator by invoking the init script with the start option:
$ /etc/rc3.d/S99procallator start
This will start the procallator script as a daemon process, and the script will write performance data to the directory defined in the procallator script’s DEST_DIR variable every 5 minutes (this is tunable). The performance files will contain the name proccol-YYYY-MM-DD-INDEX, and one file will be produced each day. To graph the data in the procallator files, you can use orca and the procallator.cfg file that is in the $PREFIX/data_gathers/procallator directory. I placed a sample set of performance graphs on my website, and you can reference the article monitoring LDAP performance article for details on setting up orca to graph data. I digs me some procallator!

Courtesy : http://prefetch.net/blog/index.php/2007/06/15/monitoring-linux-server-performance-with-procallator/

Using LoadAvg for Performance Optimization

Linux and Unixes have excellent metric of system load called “loadavg”. In fact load average is is 3 numbers which correspond to “load average” calculated for one five and 15 minutes. It is computed as exponential moving average so most recent load have more weight in the value than old one.

What does Load Average corresponds to ? At least on Linux it is number of processes which are in “running” state or in “uninterruptable sleep” state which typically corresponds to disk IO. You can also map LoadAvg to VMSTAT output – it is something like moving average of sum of “r” and “b” columns from VMSTAT.

Obviously minimum value for LoadAvg is zero which corresponds to completely idle system, and there is no maximum :)

First thing to understand about LoadAvg it does not really tell you if it is CPU bound load or IO bound load. For example if you have LoadAvg of 10 it may mean there are 10 processes/threads actively consuming CPU or it could be same 10 processes waiting on disk IO and you can see CPU utilization being close to zero.

Second thing is to understand LoadAvg values are relative to your system size. If you have single CPU and 1 disk loadavg of 2 can be considered significant, while if you have 16 CPUs and 2 disks Load of 4 can be light if it is CPU bound – because the system can execute much more CPU bound tasks in parallel or High if it is Disk Bound LoadAvg.

Low Load Average does not mean there are no performance problems, for example if you run single batch job on the server with MySQL, Load Average is likely to be close to 1 even if there are a lot of CPUs and Disks – system may be quite idle and performance still poor because application is not parallel enough. Similar situations can happen if there is a lot of network IO involved or if there are a lot of locks (table/row level locks) or other limiting factors such as innodb_thread_concurrency.

The most interesting question I think is how LoadAvg represent box load in terms of how much load it can handle before it becomes to slow down or being completely unable to handle the load, and it is tricky question. Both for CPUs and for Disk there are two stages request can be. It can be ether currently executing or queued for further execution. The time which is needed to complete request is sum of time it was really executed and the time it was spent in queue. As the system is loaded response time starts to increase mainly because of time requests spend waiting in various queues and waiting on locks, the time of true execution may well remain constant. This is a bit of simplifications as there are number of other effects coming in play but good enough for sake of explanation.

What does it mean from LoadAvg standpoint ? You need to understand where parallel execution continues and where waiting in the queue starts. If you have fully CPU bound workload which is rather parallel (ie many queries will run at once) and you have 4CPUs until your LoadAvg is below 4 you have low time spend waiting for CPUs to be free to do the work. There is some wait but not much. So if you have LoadAvg of 1 and your workload scales linearly with number of connections and CPUs (ie there are no row waits involved) you can assume box can handle up to 3-4 times more load before response time starts to suffer.

If however the LoadAvg is 4 already it may take rather insignificant increase to take it up to 8 and you will see some delays due to queuing. If there are 4CPUs (Cores) and loadavg is 16 for CPU bound workload it often means requests should take 4 times more to complete than they would on idle box due to waiting in the queue.

Same true for pure Disk IO bound workload with small difference of disk not being replaceable (if you’re waiting on one drive you can’t use another drive instead), and the fact disks can optimize multiple outstanding requests a bit better compared to requests coming one after another.

For mixed workload, which is what we usually see in practice you have to do some assumptions guesses or further analyzes if you want good estimates. Ie you may want to check mpstat, vmstat and iostat to see where load comes from. But the general rule remains the same – until you’re able to explore parallel abilities of the box it will perform well as soon as you need to do a lot of queuing performance starts to suffer.

Let us clarify last point – how much more load the box can handle before it overloads, loadavg skyrockets and it becomes as good as down. First for many applications request inflow is not constant – ie web site gets poor response time and users do not spend so much time on it any more so load drops. This is however temporary relive only as there are stubborn users which would not go away even with slow responding site until their browsers timeout, which is as good as site is down. There are too many variables to come with exact numbers but generally as soon as you have long queuing started it may take just 10-20% extra load to overload system, so it is better to keep loadavg low – below number of CPUs and/or disks you have.

I must note – LoadAvg is not perfect tool for the task. It is just almost always available unlike other metrics. It is best to have profiling information so you can see as response time for your requests starts to grow. As soon as it becomes to grow with no good reason I would start to worry whatever LoadAvg shows.

Courtesy : http://www.mysqlperformanceblog.com/2006/12/04/using-loadavg-for-performance-optimization/

Monday, September 6, 2010

During some QoS tests on Linux I needed to measure the traffic of the system in realtime without being able to compile any new software on it. The system had already perl installed so I googled to find a script that could monitor in/out traffic of an interface. The first script I found was this: http://perlmonks.org/?node_id=635792
While it’s actually doing what it says, it only runs just once. I wanted the script to run for a period of time. So I changed it a bit.
Here’s the outcome:
#!/usr/bin/perl
my $dev=$ARGV[0];
sub get_measures {
my $data = `cat /proc/net/dev | grep "$dev" | head -n1`;
$data =~ /$dev\:(\d+)\D+\d+\D+\d+\D+\d+\D+\d+\D+\d+\D+\d+\D+\d+\D+(\d+)\D+/;
my $recv = int($1/1024);
my $sent= int($2/1024);
return ($recv,$sent);
}
my @m1 = get_measures;
while(1) {
sleep 1;
my @m2 = get_measures;
my @rates = ($m2[0] - $m1[0], $m2[1]-$m1[1]);
foreach ('received' , ' transmit') {
printf "$_ rate:%sKB",shift @rates;
}
print "\n";
@m1=@m2;
}

I’ve changed it so that it’s:
a) running continuously until someone presses ctrl+c to stop it,
b) parsing the /proc/net/dev output instead of the ifconfig output. I think this is more efficient/fast than parsing the ifconfig output.
Sample output:
$iftraffic.pl eth0
received rate:1564KB transmit rate:71KB
received rate:1316KB transmit rate:44KB
received rate:1415KB transmit rate:48KB
received rate:1579KB transmit rate:76KB
I am sure that someone with more insight into perl than me can make it even more efficient.
You can also download a version with comments that I made so that one can make the script run for X number of repetitions instead of running until someone stops it.
http://www.void.gr/kargig/blog/wp-content/iftraffic.pl

Source : http://www.void.gr/kargig/blog/2009/05/04/iftraffic-perl-script-to-measure-inout-traffic-in-realtime/