Анализ использования памяти программой c с использованием ps aux или top - PullRequest
0 голосов
/ 08 апреля 2020

Наш учитель сказал нам выделять 500 байт в секунду и анализировать их с помощью команды

> ps aux

для linux.

Оригинальный вопрос (на немецком языке) (не стесняйтесь переводить его с Google это переводит довольно точно)

(c) Schreiben Sie ein einfaches Programm, das im Sekundentakt 500 Byte Speicher anfordert.Starten Sie das
Programm und uberprüfen Sie den Speicherplatzverbrauch zur Laufzeit.Was stellen Sie fest? Erklären Sie ihre
Beobachtung.(Hinweis: Sie können die "time.h"Bibliothek für sekundentakte Operation benutzen.)

, что переводится на английский sh:

Напишите простую программу, которая запрашивает с интервалом в одну секунду 500 байт памяти. Запустите программу и проверьте использование дискового пространства во время выполнения. Что ты заметил? (Примечание. Вы можете использовать библиотеку «time.h» для выполнения операций в течение одной секунды.)

Я выделил еще больше и сделал это быстрее, но все еще не мог видеть четких результатов, хотя я теоретически должен был.

Моя C программа (если я не теряю память) всегда использует 0,0% MEM, хотя математически предполагалось использовать больше (у меня 16 Гб оперативной памяти, 16

1024 * 1024 = 17179869184 байт, 17179869184/1000 = 17179869.184 Байт соответствуют 0,1% моей оперативной памяти, прежде чем я смог получить INT_MAX Я мог бы выделить 2147400500 байт памяти, что составляет более 0,1% моей памяти (12,4% ), но все равно показывает 0% ... на ps aux или вверху)

#include <stdio.h>
#include <time.h>
#include <stdlib.h> //for system() and malloc
time_t start;
char *job, *temp;
int printMenu(){
    //linux : clear, windows : cls, ..
    system("clear");
    printf("\nEnter: Wiederhole (fuer 60 Sekunden), Andere Zeichen: Quit\n");
    printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
}

void delay(int mics){

    clock_t timeDelay = (mics-0.9999) * CLOCKS_PER_SEC + clock();
    while(timeDelay > clock());
}

int end(){
    delay(1);
    system("ps aux --sort -pmem | grep './2c.out' >> memreport.txt");
    delay(1);
    free(job);
    time_t end = clock();
    printf("\nTotal time elapsed: end-start clock: %lf\n", (double)(end - start)/CLOCKS_PER_SEC);

    return 0;

}
int main(){
    int exitstatus;
    int x = 500;
    start = clock();
    exitstatus = system("ps aux --sort -pmem | grep './2c.out' >> memreport.txt");

    // printf("%ld cps\n", CLOCKS_PER_SEC); // 1,000,000 oder (1takt = 1 mikrosekunde)
    system("gnome-terminal -e top -t check_memory");
    printMenu();
    char s = '\n'; // enter
    job = (char *)malloc(x);
    if(job == NULL)
    {
        printf("Allocation failed!");
        return end();
    }
    while(s == '\n')
    {

        for(int i = 0; i < 990; i++)
        {
            x += 100000;
            printf("Allocating %d Bytes..\n", x);
            /*
                job = (char *)malloc(x);
                if(job == NULL)
                {
                    printf("Malloc failed!");
                    return end();
                }
            */  
            /*
            temp = realloc(job, x);
            if( temp != NULL)
            {
                job = temp;
            }
            else
            {
                printf("Reallocation failed!");
                return end();

            }
            */


            free(job);
            temp = (char *)malloc(x);
                if(temp == NULL)
                {
                    printf("Malloc failed!");
                    return end();
                }
                else
                {
                    job = temp;
                }

           delay(1);

        }

        exitstatus = system("ps aux --sort -pmem | grep './2c.out' >> memreport.txt");

        printf("\nEnter: Wiederhole (fuer 60 Sekunden), Andere Zeichen: Quit\n");

        scanf("%c", &s);
        if(exitstatus != 0)
        {
            printf("Terminal couldn't run 'ps'");
        }
    }


    return end();

}

Вывод на терминал:

Allocating 2146600500 Bytes..
Allocating 2146700500 Bytes..
Allocating 2146800500 Bytes..
Allocating 2146900500 Bytes..
Allocating 2147000500 Bytes..
Allocating 2147100500 Bytes..
Allocating 2147200500 Bytes..
Allocating 2147300500 Bytes..
Allocating 2147400500 Bytes..
Allocating -2147466796 Bytes..
Segmentation fault (core dumped)
*1024* Вывод на memreport.txt
inducti+ 21367  0.0  0.0  22948  1148 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21365  0.0  0.0   4624   784 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364  0.0  0.0   4372   708 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21364  0.0  0.0 101188  1488 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21382  0.0  0.0  22948  1108 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21380  0.0  0.0   4624   832 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364  7.0  0.0 197864  1552 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21387  0.0  0.0  22948  1048 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21385  0.0  0.0   4624   800 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 10.6  0.0 294544  1552 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21390  0.0  0.0  22948  1080 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21388  0.0  0.0   4624   772 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 14.0  0.0 391224  1552 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21393  0.0  0.0  22948  1052 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21391  0.0  0.0   4624   804 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 18.0  0.0 487904  1552 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21396  0.0  0.0  22948  1008 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21394  0.0  0.0   4624   808 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 16.0  0.0 584584  1552 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21399  0.0  0.0  22948  1016 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21397  0.0  0.0   4624   820 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 18.7  0.0 681264  1552 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21402  0.0  0.0  22948  1084 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21400  0.0  0.0   4624   800 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 21.5  0.0 777944  1552 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21405  0.0  0.0  22948  1104 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21403  0.0  0.0   4624   804 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 24.2  0.0 874624  1552 pts/0    S+   21:40   0:00 ./2c.out
inducti+ 21408  0.0  0.0  22948  1060 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21406  0.0  0.0   4624   804 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 27.0  0.0 971304  1552 pts/0    S+   21:40   0:01 ./2c.out
inducti+ 21411  0.0  0.0  22948  1008 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21409  0.0  0.0   4624   828 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 29.5  0.0 1067984 1552 pts/0    S+   21:40   0:01 ./2c.out
inducti+ 21414  0.0  0.0  22948  1004 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21412  0.0  0.0   4624   820 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 32.5  0.0 1164664 1552 pts/0    S+   21:40   0:01 ./2c.out
inducti+ 21417  0.0  0.0  22948  1088 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21415  0.0  0.0   4624   876 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 35.2  0.0 1261344 1552 pts/0    S+   21:40   0:01 ./2c.out
inducti+ 21420  0.0  0.0  22948   968 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21418  0.0  0.0   4624   776 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 30.2  0.0 1358024 1552 pts/0    S+   21:40   0:01 ./2c.out
inducti+ 21423  0.0  0.0  22948  1008 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21421  0.0  0.0   4624   808 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 32.6  0.0 1454700 1552 pts/0    S+   21:40   0:01 ./2c.out
inducti+ 21426  0.0  0.0  22948  1036 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21424  0.0  0.0   4624   784 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 34.8  0.0 1551380 1552 pts/0    S+   21:40   0:01 ./2c.out
inducti+ 21429  0.0  0.0  22948  1004 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21427  0.0  0.0   4624   812 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 30.8  0.0 1648060 1552 pts/0    S+   21:40   0:01 ./2c.out
inducti+ 21432  0.0  0.0  22948  1032 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21430  0.0  0.0   4624   820 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 32.8  0.0 1744740 1552 pts/0    S+   21:40   0:01 ./2c.out
inducti+ 21435  0.0  0.0  22948  1088 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21433  0.0  0.0   4624   772 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 34.6  0.0 1841420 1552 pts/0    S+   21:40   0:02 ./2c.out
inducti+ 21438  0.0  0.0  22948  1000 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21436  0.0  0.0   4624   820 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 36.6  0.0 1938100 1552 pts/0    S+   21:40   0:02 ./2c.out
inducti+ 21441  0.0  0.0  22948  1052 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21439  0.0  0.0   4624   784 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 38.5  0.0 2034780 1552 pts/0    S+   21:40   0:02 ./2c.out
inducti+ 21444  0.0  0.0  22948  1004 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21442  0.0  0.0   4624   832 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 21364 34.1  0.0   4504  1552 pts/0    S+   21:40   0:02 ./2c.out
inducti+ 21447  0.0  0.0  22948  1004 pts/0    S+   21:40   0:00 grep ./2c.out
inducti+ 21445  0.0  0.0   4624   804 pts/0    S+   21:40   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt

Если я не использую free и использую один из закомментированных блоков для выделения памяти, My% MEM увеличивается до 0,04%

job = (char *)malloc(x);
if(job == NULL)
{
   printf("Malloc failed!");
   return end();
}

Но это утечка памяти.

Показывает ли результат команды ps aux и top только утечку памяти, если да, то как это имеет смысл?

Я пытался найти ответы в Google, но не смог найти ничего удовлетворительного, я верю в поиск в Google, пожалуйста, не просто дайте ссылку на уже предоставленный ответ, который явно не применим к этому.

Некоторые заключительные примечания

Я знаю, что функция delay () не задерживается на 1 секунду, но меньше, я сделал это временно так, только чтобы увидеть результаты быстрее

если я использую альтернативный блок кода для выделения памяти, который я показал, я также получаю ошибку «терминал не может запустить« ps »», причина которой мне неясна ...

Я ценю любую помощь, которую вы можете предложить, спасибо :) И я извиняюсь, если вопрос слишком сложный или неясный.

Редактировать: Callo c не работал, но попытался инициализировать каждый блок с 'a', и память увеличилась до 1,1%

inducti+ 25073  0.0  0.0  22948  1104 pts/2    S+   23:01   0:00 grep ./2c.out
inducti+ 25071  0.0  0.0   4624   804 pts/2    S+   23:01   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 25070  0.0  0.0   4372   716 pts/2    S+   23:01   0:00 ./2c.out
inducti+ 25070  101  0.6 101188 98212 pts/2    S+   23:01   0:18 ./2c.out
inducti+ 25091  0.0  0.0  22948  1052 pts/2    S+   23:02   0:00 grep ./2c.out
inducti+ 25089  0.0  0.0   4624   880 pts/2    S+   23:02   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 25070 94.9  1.1 197864 194900 pts/2   S+   23:01   1:13 ./2c.out
inducti+ 25103  0.0  0.0  22948  1028 pts/2    S+   23:02   0:00 grep ./2c.out
inducti+ 25101  0.0  0.0   4624   820 pts/2    S+   23:02   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt
inducti+ 25070 91.3  1.1 197864 194900 pts/2   S+   23:01   1:13 ./2c.out
inducti+ 25107  0.0  0.0  22948  1052 pts/2    S+   23:03   0:00 grep ./2c.out
inducti+ 25105  0.0  0.0   4624   780 pts/2    S+   23:03   0:00 sh -c ps aux --sort -pmem | grep './2c.out' >> memreport.txt

Но я все еще мог бы использовать некоторые объяснения, почему это все происходит.

...