]> www.ginac.de Git - ginac.git/blob - check/fcntimer.cpp
152ec67d6745c5b6908f1dcdf253bad4d1c43a66
[ginac.git] / check / fcntimer.cpp
1 /** @file fcntimer.cpp
2  *
3  *  Function execution timer.
4  *
5  *  GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22
23 #include <stdio.h>
24 #include <sys/resource.h>
25
26
27 // fcntimer() is a little wrapper around GiNaC's automated checks.  All those
28 // functions are passed void and return unsigned.  fcntimer() accepts one such
29 // function fcn(), returns its result and as a side-effect prints to stdout how
30 // much CPU time was consumed by fcn's execution in the fashion "(0.07s)\n".
31 unsigned fcntimer(unsigned fcn())
32 {
33     unsigned fcnresult;
34     struct rusage used1, used2;
35     double elapsed;
36
37     // time the execution of the function:
38     getrusage(RUSAGE_SELF, &used1);
39     fcnresult = fcn();
40     getrusage(RUSAGE_SELF, &used2);
41
42     // add elapsed user and system time in microseconds:
43     elapsed = ((used2.ru_utime.tv_sec - used1.ru_utime.tv_sec) +
44                (used2.ru_stime.tv_sec - used1.ru_stime.tv_sec) +
45                (used2.ru_utime.tv_usec - used1.ru_utime.tv_usec) / 1e6 +
46                (used2.ru_stime.tv_usec - used1.ru_stime.tv_usec) / 1e6);
47
48     printf("(%.2fs)\n", elapsed);
49
50     return fcnresult;
51 }