damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

elapsed.h (2144B)


      1 #ifndef ELAPSED_H
      2 #define ELAPSED_H
      3 
      4 #ifdef __cplusplus
      5 extern "C" {
      6 #endif
      7 
      8 #include <stdio.h>
      9 
     10 /* Based on http://stackoverflow.com/a/8583395 */
     11 #if !defined(_WIN32)
     12 #include <sys/time.h>
     13 static double elapsed_realtime(void) { // returns 0 seconds first time called
     14     static struct timeval t0;
     15     struct timeval tv;
     16     gettimeofday(&tv, 0);
     17     if (!t0.tv_sec)
     18         t0 = tv;
     19     return (double)(tv.tv_sec - t0.tv_sec) + (double)(tv.tv_usec - t0.tv_usec) / 1e6;
     20 }
     21 #else
     22 #include <windows.h>
     23 #ifndef FatalError
     24 #define FatalError(s) do { perror(s); exit(-1); } while(0)
     25 #endif
     26 static double elapsed_realtime(void) { // granularity about 50 microsecs on my machine
     27 	static LARGE_INTEGER freq, start;
     28     LARGE_INTEGER count;
     29     if (!QueryPerformanceCounter(&count))
     30         FatalError("QueryPerformanceCounter");
     31     if (!freq.QuadPart) { // one time initialization
     32         if (!QueryPerformanceFrequency(&freq))
     33             FatalError("QueryPerformanceFrequency");
     34         start = count;
     35     }
     36     return (double)(count.QuadPart - start.QuadPart) / freq.QuadPart;
     37 }
     38 #endif
     39 
     40 /* end Based on stackoverflow */
     41 
     42 static int show_benchmark(const char *descr, double t1, double t2, size_t size, int rep, const char *reptext)
     43 {
     44     double tdiff = t2 - t1;
     45     double nstime;
     46 
     47     printf("operation: %s\n", descr);
     48     printf("elapsed time: %.3f (s)\n", tdiff);
     49     printf("iterations: %d\n", rep);
     50     printf("size: %lu (bytes)\n", (unsigned long)size);
     51     printf("bandwidth: %.3f (MB/s)\n", (double)rep * (double)size / 1e6 / tdiff);
     52     printf("throughput in ops per sec: %.3f\n", rep / tdiff);
     53     if (reptext && rep != 1) {
     54         printf("throughput in %s ops per sec: %.3f\n", reptext, 1 / tdiff);
     55     }
     56     nstime = tdiff * 1e9 / rep;
     57     if (nstime < 1000) {
     58         printf("time per op: %.3f (ns)\n", nstime);
     59     } else if (nstime < 1e6) {
     60         printf("time per op: %.3f (us)\n", nstime / 1000);
     61     } else if (nstime < 1e9) {
     62         printf("time per op: %.3f (ms)\n", nstime / 1e6);
     63     } else {
     64         printf("time per op: %.3f (s)\n", nstime / 1e9);
     65     }
     66     return 0;
     67 }
     68 
     69 #ifdef __cplusplus
     70 }
     71 #endif
     72 
     73 #endif /* ELAPSED_H */