Grid 0.7.0
Profiling.h
Go to the documentation of this file.
1 /*************************************************************************************
2
3 Grid physics library, www.github.com/paboyle/Grid
4
5 Source file: ./lib/util/Profiling.h
6
7 Copyright (C) 2018
8
9 Author: Guido Cossu <guido.cossu@ed.ac.uk>
10
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
15
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License along
22 with this program; if not, write to the Free Software Foundation, Inc.,
23 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
25 See the full license in the file "LICENSE" in the top level distribution directory
26 *************************************************************************************/
27 /* END LEGAL */
28
29#ifndef GRID_PERF_PROFILING_H
30#define GRID_PERF_PROFILING_H
31
32#include <sstream>
33#include <iostream>
34#include <functional>
35#include <fcntl.h>
36#include <sys/stat.h>
37#include <sys/wait.h>
38#include <sys/types.h>
39#include <unistd.h>
40#include <signal.h>
41
42struct System
43{
44 static void profile(const std::string& name,std::function<void()> body) {
45 std::string filename = name.find(".data") == std::string::npos ? (name + ".data") : name;
46
47 // Launch profiler
48 pid_t pid;
49 std::stringstream s;
50 s << getpid();
51 pid = fork();
52 if (pid == 0) {
53 auto fd=open("/dev/null",O_RDWR);
54 dup2(fd,1);
55 dup2(fd,2);
56 exit(execl("/usr/bin/perf","perf","record","-o",filename.c_str(),"-p",s.str().c_str(),nullptr));
57 }
58
59 // Run body
60 body();
61
62 // Kill profiler
63 kill(pid,SIGINT);
64 waitpid(pid,nullptr,0);
65 }
66
67 static void profile(std::function<void()> body) {
68 profile("perf.data",body);
69 }
70};
71
72#endif // GRID_PERF_PROFILING_H
static void profile(const std::string &name, std::function< void()> body)
Definition Profiling.h:44
static void profile(std::function< void()> body)
Definition Profiling.h:67