Blog do Julio

Hacks, tutoriais e dicas

Time

| Comments

No ZSH: julio@acer ~> time ./programa
Hello World! ./programa 1.54s user 0.03s system 97% cpu 1.611 total

julio@acer ~> type -a time
time is a reserved word

julio@acer ~> which time
time: shell reserved word

julio@acer ~> sudo pacman -S time

julio@acer ~> /usr/bin/time ./programa 
Hello World!
1.39user 0.00system 0:01.41elapsed 99%CPU (0avgtext+0avgdata 8940maxresident)k
0inputs+0outputs (0major+758minor)pagefaults 0swaps

man time

julio@acer ~> /usr/bin/time -v ./programa
Hello World!
    Command being timed: "./programa"
    User time (seconds): 1.57
    System time (seconds): 0.05
    Percent of CPU this job got: 99%
    Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.63
    Average shared text size (kbytes): 0
    Average unshared data size (kbytes): 0
    Average stack size (kbytes): 0
    Average total size (kbytes): 0
    Maximum resident set size (kbytes): 8936
    Average resident set size (kbytes): 0
    Major (requiring I/O) page faults: 0
    Minor (reclaiming a frame) page faults: 758
    Voluntary context switches: 1
    Involuntary context switches: 181
    Swaps: 0
    File system inputs: 0
    File system outputs: 3160
    Socket messages sent: 0
    Socket messages received: 0
    Signals delivered: 0
    Page size (bytes): 4096
    Exit status: 0

julio@acer ~> /usr/bin/time -p ./programa
Hello World!
real 1.45
user 1.44
sys 0.00

alias time='/usr/bin/time -p'

C/C++

As precisões do time e do /usr/bin/time não são muito boas se você quiser fazer um profiling mais sério ou quiser verificar o tempo gasto por uma parte específica do código e não do programa todo. Para esses casos, no Linux e FreeBSD, podemos usar a função clock_gettime da time.h.

Olhando o arquivo /usr/include/time.h int clock_gettime(clockid_t clk_id, struct timespec *tp);

CLOCK_REALTIME: Relógio do sistema. CLOCK_MONOTONIC: CLOCK_PROCESS_CPUTIME_ID: Timer fornecido pelo CPU a cada processo. CLOCK_THREAD_CPUTIME_ID: Timer fornecido pelo CPU a cada thread.

#include <ctime>

timespec diff(timespec start, timespec end)
{
    timespec temp;
    if (end.tv_nsec - start.tv_nsec < 0)
    {
        temp.tv_sec = end.tv_sec - start.tv_sec-1;
        temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
    }
    else
    {
        temp.tv_sec = end.tv_sec - start.tv_sec;
        temp.tv_nsec = end.tv_nsec - start.tv_nsec;
    }
    return temp;
}

int main()
{
    timespec time1, time2;
    clock_gettime(CLOCK_REALTIME, &time1);

    // ... ... ...

    clock_gettime(CLOCK_REALTIME, &time2);

    cout << diff(time1,time2).tv_sec << ":"
         << diff(time1,time2).tv_nsec << endl;

    return 0;
}

Esse programa deve ser compilado usando g++ -lrt -o programa programa.cpp, o resultado será algo assim: julio@acer ~> ./programa 0:7674929

Comments