プログラムの中で時間を測定したり、 日付を利用したり、カレンダーを利用する方法をメモしておきます。 WindowsやLinuxの情報は、世の中にいっぱいあると思いますので、 Mac OS XやiOSのプログラミングを中心に書いておきます。
http://www.bugbearr.jp/?C%E8%A8%80%E8%AA%9E%2F%E6%97%A5%E6%99%82
にあるような、Unix標準の呼び出しが使える。 たとえば、以下は、画面表示が出てから人が反応する時間を測定するプロフラムである。
#include <sys/time.h> #include <stdio.h> inline double gettimeofday_sec() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + (double)tv.tv_usec*1e-6; } int main(void) { double t1, t2; sleep(5); printf("hit now"); t1=gettimeofday_sec(); getchar(); t2=gettimeofday_sec(); printf("time = %10.3f\n", t2 - t1); return 0; }
Mac OS X やiOS (iphone, ipad, ipod-touch) で使えます。
NSTimeInterval oldtime, newtime; oldtime = [NSDate timeIntervalSinceReferenceDate]; //ここで何かをする newtime = [NSDate timeIntervalSinceReferenceDate]; NSLog(@"interval is %.3f", newtime - oldtime);
ここで、newtimeとoldtimeの差が秒単位の経過時間になります。 NSTimeInterval は、NSDate.hでdoubleとして定義されています。単位は秒、範囲は1万年以上、小数点以下はミリ秒以下までの精度があるそうです。
NSDate *today = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *now = [calendar components: NSYearCalendarUnit | //.yearが必要な場合指定 NSMonthCalendarUnit | //,monthが必要な場合指定 NSDayCalendarUnit | //(以下同様) NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit fromDate:today]; NSLog(@"%d\n",now.year); NSLog(@"%d\n",now.month); NSLog(@"%d\n",now.day); NSLog(@"%d\n",now.hour); NSLog(@"%d\n",now.minute); NSLog(@"%d\n",now.second); NSLog(@"%d\n",now.week); NSLog(@"%d\n",now.weekday); //1から7, 1が日曜日
この結果、
2011-07-03 12:56:03.878 hello[1446:a0f] 2011 2011-07-03 12:56:03.878 hello[1446:a0f] 7 2011-07-03 12:56:03.879 hello[1446:a0f] 3 2011-07-03 12:56:03.879 hello[1446:a0f] 12 2011-07-03 12:56:03.879 hello[1446:a0f] 56 2011-07-03 12:56:03.879 hello[1446:a0f] 3 2011-07-03 12:56:03.880 hello[1446:a0f] 28 2011-07-03 12:56:03.880 hello[1446:a0f] 1
となります。得られる値はすべてNSIntegerです。
本年の1月1日を表すNSDate変数jan1stというのを作って、 NSTime Intervalを計算しています。 この結果(secofyear)は1月1日からの秒数です。 そこで、一日の秒数で割り算して、さらに1月1日を1とするよう+1しています。
NSDate *today = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *now = [calendar components:NSYearCalendarUnit fromDate:today]; //calculate days of the year NSDate *jan1st = [[NSDate alloc] initWithString: [NSString stringWithFormat:@"%d-01-01 00:00:00 +0900",now.year]]; NSTimeInterval secofyear = [today timeIntervalSinceDate:jan1st ]; int days = (int)(secofyear / (60 * 60 * 24)) + 1; //Jan 1st is 1
以下は、自分自身のメソッド、mymethodを毎秒呼び出す方法です。
// This starts the timer which fires the mymethod // method every 1.0 seconds myTicker = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(mymethod) userInfo: nil repeats: YES];