I am writing a network program which can calculate accurate data packet rate (packet per second, frame per second, bps). Now i have a device called testcenter which can send accurate flow to a specific pc (protocol is UDP/IP) on Linux, i like to know the accurate pps(packets per second) with my program , i have considered the gettimeofday(&start,NULL)
function before i call recvfrom()
and update the counter for packets, after that call gettimeofday(&end,NULL)
and get the pps rate. I hope there is better solution than this since the user/kernel barrier is traversed on system calls.
Best regards.

- 365
- 1
- 3
- 8
-
2Hello and welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist). You might also want to learn what a [SSCCE](http://sscce.org/) is. – Some programmer dude Jan 13 '14 at 06:47
2 Answers
I think you should use clock_gettime() with CLOCK_MONOTONIC_COARSE. But it will only be accurate till the last tick .. So may be off by 10s of millisec. But its definitely faster that using it with CLOCK_MONOTONIC_RAW. You can also use gettimeofday but clock_gettime with CLOCK_MONOTONIC_RAW is slightly faster and higher resolution than gettimeofday. Also gettimeofday() gives wall clock time, which might change even for daylight saving ... I don't think you should use it to measure traffic rate.

- 948
- 6
- 10
Your observation that gettimeofday
switches to kernel mode is incorrect for Linux on a few popular architectures due to the use of vsyscalls. Clearly using gettimeofday
here is not a bad option. You should however consider using a monotonic clock, see man 3 clock_gettime
. Note that clock_gettime
is not yet converted to vsyscall for as many architectures as gettimeofday
.
Beyond this option you may be able to set the SO_TIMESTAMP
socket option and obtain precise timestamps via recvmsg
.

- 6,578
- 2
- 31
- 67
-
Thanks! the SO_TIMESTAMP socket option is a much better way solved my problem, the kernel gives the incoming data packet once the MAC rx the frame, i think it's precise. – xiaozhu Mar 03 '14 at 02:16