Friday, April 29, 2011

How to find the size of a file in C++?

We need to use the combination of fseek and ftell functions. Here's one such implementation. This implementation will return a '-1' in case it'll not be able to open the file, else returns the size of the file (in B).

#include <stdio.h>
/**
 * @brief Finds the size of the file (in B)
 * @param file name of the file
 * @return if file-open fails, returns a value of -1; else size of the file.
 */
int sizeOfFile(const char *file) {
    FILE* fp = fopen(file, "rb");
    if(fp == NULL) { return -1; }
    fseek(fp, 0, SEEK_END);
    int i = ftell(fp);
    fclose(fp);
    return i;
}

I tried to verify the performance of the above function, using the piece of code below:
int main(int argc, char** argv) {
    if(argc != 2) {
        fprintf(stderr, "USAGE: %s <fileToBeRead>\n", argv[0]);
        return 1;
    }
    for(int i=0;i<10000;i++) {
        sizeOfFile(argv[1]);
    }
    return 0;
}

I copied above 2 pieces of code into a file named 'test_perf.cpp'. Then, I compiled using the command: 'g++ -o perf test_perf.cpp' in cygwin version 1.7. Here's my result: [System: Dell Latitude E6400, Win7, 32b]
$ time ./perf.exe perf.exe
real    0m2.677s
user    0m0.342s
sys     0m1.887s
$ stat perf.exe
  File: `perf.exe'
  Size: 19596           Blocks: 20         IO Block: 65536  regular file
 .... some more outputs hidden for privacy reasons ....

Monday, April 18, 2011

cutop: GPU version of 'top'

Here's a tool I wrote today for for mimicking the functionality of the famous unix tool 'top'. The idea is to give the user the capability to monitor how the resource usage is going on in the GPU's. Currently, this tool does not do much, but only monitors the memory usage of the GPU's. In the future releases of this tool, I'm planning to add more functionalities. Ofcourse, assuming that I get hold of the NVML API as soon as possible! (fingers crossed). 

But till then, I've hosted the project over github and you can access the source code from here: (read-only) 'git://github.com/teju85/cutop.git'.

Wednesday, April 6, 2011

Minimum resolution of the C 'clock' function

Here is the C program to find out the minimum resolution of the 'clock' function on your system.

#include <time.h>
#include <stdio.h>

int main(int argc, char** argv) {
    clock_t a, b;
    a = b = clock();
    while(a == b) {
        b = clock();
    }
    printf("Minimum resolution by 'clock()' = %lf s\n",
           ((double) (b - a))/CLOCKS_PER_SEC);
    return 0;
}

How to compile? (assuming that you have stored this program in a file named 'minRes.c')
gcc -o minRes minRes.c

How to run?
minRes

On my system (Dell Latitude E6400, running Win7), I got this to be about 15ms, on an average.
What about you?