Note: A simple 32bits checksum calculator

// CHKSUM32.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    FILE *pf;
    register unsigned char buff[4*1024];
    register unsigned int  chksum;
    register unsigned int  size;

    if (argc < 2)
    {
        _tprintf(_T("Need filename parameter!n"));
        return 1;
    }

    _tfopen_s(&pf, argv[1], _T("rb"));
    if (NULL == pf)
    {
        _tprintf(_T("Cannot open %sn"),argv[1]);
        return 2;
    }
    chksum = 0;
    size = 0;
    for(;;)
    {
        int len = (int)fread(buff, sizeof(unsigned char), sizeof(buff), pf);
        bool exit = (sizeof(buff) == len) ? false : true;
#if 1
        // simple
        for (int i=0; i < len; i++)
            chksum += buff[i];
#elif 0
        // style 1
        for (int i=0; i < (len-7); i+=8)
        {
            chksum += buff[i+0];
            chksum += buff[i+1];
            chksum += buff[i+2];
            chksum += buff[i+3];
            chksum += buff[i+4];
            chksum += buff[i+5];
            chksum += buff[i+6];
            chksum += buff[i+7];
        }

        switch(len%8) {
        case 7: chksum += buff[len-7];
        case 6: chksum += buff[len-6];
        case 5: chksum += buff[len-5];
        case 4: chksum += buff[len-4];
        case 3: chksum += buff[len-3];
        case 2: chksum += buff[len-2];
        case 1: chksum += buff[len-1];
        }
#elif 0
        // style 2, use duff device pattern
        register int n = (len+7) / 8;
        register unsigned char* p = buff;
        switch(len%8) {
        case 0: do {
                chksum += *p++;
        case 7: chksum += *p++;
        case 6: chksum += *p++;
        case 5: chksum += *p++;
        case 4: chksum += *p++;
        case 3: chksum += *p++;
        case 2: chksum += *p++;
        case 1: chksum += *p++;
                } while(–n > 0);
        }
#endif
        size += len;
        if (exit) break;
    }
    fclose(pf);
    _tprintf(_T("File: %s, Checksum : 0x%08X, Length:0x%08Xn"), argv[1], chksum, size);
    return 0;
}

test result

CPU : Core 2, T5600

OS: Windows XP Sp3 x86

Test file size: 1GB

compiler: Visual C++ 2005,

compiler option:

/O2 /GL /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /FD /EHsc /MD /Yu"stdafx.h" /Fp"ReleaseCHKSUM32.pch" /FAs /Fa"Release\" /Fo"Release\" /Fd"Releasevc80.pdb" /W3 /nologo /c /Wp64 /Zi /TP /errorReport:prompt

Test method: run 3 times to sum by each code style

simple : 5.8 sec

style 1 :  6. 42 sec

style 2 : 6.6 sec

So simple is better!

廣告

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

%d 位部落客按了讚: