File: memusage.c

package info (click to toggle)
gmp-ecm 7.0.4+ds-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 4,728 kB
  • sloc: asm: 36,431; ansic: 34,057; xml: 885; python: 799; sh: 698; makefile: 348
file content (76 lines) | stat: -rw-r--r-- 1,897 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* Memory usage utilities.

Copied from CADO-NFS.

This file is part of the ECM Library.

The ECM Library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at your
option) any later version.

The ECM Library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
License for more details.

You should have received a copy of the GNU Lesser General Public License
along with the ECM Library; see the file COPYING.LIB.  If not, see
http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */

#ifndef _WIN32

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include "ecm-impl.h"

/* Returns peak memory usage, in KB
 * This is the VmPeak field in the status file of /proc/pid/ dir
 * This is highly non portable.
 * Return -1 in case of failure.
 */
long
PeakMemusage (void)
{
  pid_t pid = getpid ();

  char str[1024];
  char *truc;
  snprintf (str, 1024, "/proc/%d/status", (int) pid);

  FILE *file;
  file = fopen (str, "r");
  if (file == NULL)
    return -1; /* for example on Mac OS X */

  long mem;
  for(;;)
    {
      truc = fgets (str, 1023, file);
      if (truc == NULL)
	return -1; /* for example on FreeBSD */
      int ret = sscanf (str, "VmPeak: %ld", &mem);
      if (ret == 1)
        {
          fclose (file);
          return mem;
        }
    }
}

#else

#include <windows.h>
#include <psapi.h>

long
PeakMemusage (void)
{
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
    return (long)(info.PeakWorkingSetSize >> 10);
}

#endif