Linux time命令输出中real,user和sys的含义

The meaning of real, user, and sys in output of Linux time command

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
$ time ./Test

real    0m2.906s
user    0m2.887s
sys     0m0.017s

这是程序代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <map>

void func_a() {
    std::map<int, int> m;
    for (unsigned int i = 0; i < 10000; i++) {
        m.insert(std::pair<int, int>(i, i));
    }
}

void func_b() {
    std::map<int, int> m;
    for (unsigned int i = 0; i < 1000000; i++) {
        m.insert(std::pair<int, int>(i, i));
    }
}

int main() {
    func_a();
    func_b();
    return 0;
}


如果您查看手册页(man time页),其中说明:

The time command runs the specified program command with the given arguments. When command finishes, time writes a message to standard output giving timing statistics about this program run. These statistics consist of (i) the elapsed real time between invocation and termination, (ii) the user CPU time (the sum of the tms_utime and tms_cutime values in a struct tms as returned by times(2)), and (iii) the system CPU time (the sum of the tms_stime and tms_cstime values in a struct tms as returned by times(2)).

不过,基本上,user时间是指程序在CPU上运行的时间,而sys时间是指程序等待操作系统为其执行任务的时间。如果您对基准测试感兴趣,那么使用user + sys是个好时机。real可能会受到其他运行过程的影响,而且更不一致。