Issue
I want to write a program that sends network's current received packet cnt/byte.
I get these data from /proc/net/dev.
But I can't decide what type to store these data.
I just have feeling that using unsigned long long int is wasteful.
Are there limit for received packet cnt/byte like RLIMIT_*?
Solution
uint64_t
, uint_fast64_t
, or unsigned long long
, are the correct types to use here. The first two are available from <stdint.h>
or <inttypes.h>
, and are what I'd recommend. unsigned long long
is perfectly acceptable too. [*]
You are suffering from a misguided instinct towards premature optimization.
Even if you had a thousand of these counters – and you usually do not –, they would take a paltry amount of RAM, some 8192 bytes. This is a tiny fraction of the RAM use of a typical userspace process, because even the standard C library (especially functions like printf()
; and anything that does file I/O using <stdio.h>
) uses a couple of orders of magnitude more.
So, when you worry about how much memory you're "wasting" by using an unsigned integer type that might be larger than strictly necessary for most cases, you're probably wasting an order of magnitude more by not choosing a better approach or a better algorithm in the first place.
It is make-work worry. There are bigger things you are not thinking about all yet (because you lack the experience or knowledge or both) that affect the results you might be thinking of –– efficiency, memory footprint, run time to complete the task at hand –– often an order of magnitude more than those small details. You need to learn to think of the big picture, instead: Is this needed? Is this useful, or is there a better way to look at this?
[*] You can verify this by looking at how the data is generated, by the net/core/net-procfs.c:dev_seq_printf_stats()
, as well as look at the data structure, include/uapi/linux/if_link.h:struct rtnl_link_stats64
.
The __u64
type is how the Linux kernel calls the type, and %llu
is how the Linux kernel seq_printf()
implementation formats 64-bit unsigned integers.)
Answered By - Blabbo the Verbose Answer Checked By - David Goodson (WPSolving Volunteer)